home *** CD-ROM | disk | FTP | other *** search
Wrap
Text File | 2008-07-01 | 152.9 KB | 4,929 lines
/* ***** BEGIN LICENSE BLOCK ***** EULA Terms of use The FootieFox - Boris Ruf and Jan Schulz-Hofen GbR (ôFootieFoxö) grants you the non-transferable, non-exclusive and revocable right to use the FootieFox Software free of charge, for your personal, non-commercial use only, subject to this licensing agreement. However, you may not use the FootieFox Software in any manner that could overburden, impair or damage the FootieFox Web Service (e.g., you are not allowed to use the FootieFox Software in an automated manner). Intellectual Property After obtaining written consent of FootieFox by e-mail (contact@footiefox.com) you are permitted to offer the FootieFox Software as a whole, without any modifications and free of charge for download on your website other than footiefox.com. You may not lease, rent or sell the FootieFox Software or the information presented to you through the FootieFox Software. Furthermore, you may not sublicense or otherwise transfer any right in the FootieFox Software. You agree not to modify, adapt, translate, decompile, reverse engineer, disassemble or otherwise attempt to derive source code from the FootieFox Software. Distributing or creating derivative works based on the FootieFox Software is expressly not permitted. You also agree to not remove, obscure, or alter FootieFoxÆ and or any third partyÆs copyright notice, trademarks, or other proprietary rights notices presented through or contained in the FootieFox Software. Disclaimer of Warranties The FootieFox Software is provided free of charge and with no warranties whatsoever. FootieFox and any third party who provides its service through the FootieFox Software disclaim any responsibility for any harm resulting from the use of the FootieFox Software and/or any service provided by any third party through the FootieFox Software. THE FOOTIEFOX SOFTWARE IS PROVIDED ôAS ISö WITH ALL FAULTS AND WITH NO WARRANTIES WHATSOEVER. FOOTIEFOX EXPRESSLY DISCLAIMS ALL WARRANTIES OF ANY KIND, WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES THAT THE PRODUCT IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE AND NON-INFRINGING. FOOTIEFOX AND THIRD PARTIES WHO PROVIDE SERVICE THROUGH THE FOOTIEFOX SOFTWARE DISCLAIM ANY WARRANTIES REGARDING THE SECURITY, RELIABILITY, TIMELINESS, AND PERFORMANCE OF THE FOOTIEFOX SOFTWARE AND/OR THE INFORMATION PRESENTED TO YOU THROUGH THE FOOTIEFOX SOFTWARE. YOU UNDERSTAND AND AGREE THAT YOU BEAR ENTIRE RISK AS TO THE FITNESS, THE QUALITY AND THE PERFORMANCE OF THE PRODUCT AND THAT YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGES TO YOUR COMPUTER SYSTEM OR LOSS OF DATA THAT RESULTS FROM THE DOWNLOAD OR USE OF THE FOOTIEFOX SOFTWARE. IN SOME COUNTRIES THE EXCLUSION OR LIMITATION OF IMPLIED WARRANTIES IS NOT ALLOWED, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. Limitation of Liability TO THE EXTENT PERMITTED BY LAW, FOOTIEFOX OR ANY THIRD PARTY WILL NOT BE LIABLE FOR ANY INDIRECT, SPECIAL, INCIDENTAL, CONSEQUENTIAL OR EXEMPLARY DAMAGES ARISING OUT OF OR IN ANY WAY RELATING TO THIS LICENSING AGREEMENT OR THE USE OF OR INABILITY TO USE THE FOOTIEFOX SOFTWARE, INCLUDING WITHOUT LIMITATION DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, LOST PROFITS, LOSS OF DATA, AND COMPUTER FAILURE OR MALFUNCTION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES AND REGARDLESS OF THE THEORY (E.G. CONTRACT OR TORT) UPON WHICH SUCH CLAIM IS BASED. IN SOME COUNTRIES THE EXCLUSION OR LIMITATION OF LIABILITY FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES IS NOT ALLOWED, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. Other Terms The present license agreement will be governed by and construed in accordance with the laws of the Federal Republic of Germany and shall not be governed by the United Nations Convention on the International Sale of Goods. The courts of Berlin shall have exclusive jurisdiction. If any part of this license agreement is held invalid or unenforceable, that part will be construed to reflect the partiesÆ original intent, and the remaining portions will remain in full force and effect. * ***** END LICENSE BLOCK ***** */ var iFootieFox = null; var windowfocused = true; var goalAlertHeight = 0; var sliders = new Array(); var leagueBaseRefreshed = 0; var leagueUpdateRefreshed = 0; var failedLeagues = 0; var FootieFoxSliderAction = false; //debug switch var footiefox_d = 0; function ffLoad() { whereIsFootieFox(); iFootieFox = new FootieFox(); iFootieFox.init(); //var oPrefService = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranchInternal); var oDefPref = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getDefaultBranch("general.useragent."); } function ffUnload() { //unregister observers iFootieFox.myObservers.unregister(); iFootieFox.ffTimer.cancel(); iFootieFox.ffRotationTimer.cancel(); iFootieFox = null; } function FootieFox () { return this; } FootieFox.prototype = { prefNode: null, dictionary: null, firstExtension: false, whatsOnCalled: true, myLeagues: null, myTeams: null, myScoreboard: new Array(), activeLeagues: null, leagueTimestamps: null, redirectURL: "http://redirect.footiefox.com/", first_apiURL: "http://api2.footiefox.com/", mediaURL: "http://media.footiefox.com/", searchEngineURL: "http://en.footiefox.com/files/footiefox.xml", imagesSubdirectory: "", cacheFolder: "footiefoxCache20", rotation: false, selectedMatch: null, rotationTimer: null, soundPlayer: null, tmpDir: null, updateInterval: 16000, messageTimer: null, iframeTimer: new Array(), lastMessage: 0, messages: null, banner: null, scoreAds: null, scoreAd: null, availableHosts: new Array(), ETchecking: false, menu_visible: false, failedConnections: 0, lastUpdate:0, init: function() { //openDialog("chrome://footiefox/content/wizard.xul", "wizard", "chrome,dialog"); //initialize preferences var gDBTPrefService = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService); this.prefNode = gDBTPrefService.getBranch("extensions.footiefox."); //if preferences not available set default preferences if ( !this.prefNode.prefHasUserValue("alertmode") ) this.prefNode.setCharPref("alertmode", "league"); if ( !this.prefNode.prefHasUserValue("leaguestofollow") ) this.prefNode.setCharPref("leaguestofollow", ""); if ( !this.prefNode.prefHasUserValue("teamstofollow") ) this.prefNode.setCharPref("teamstofollow", ""); if ( !this.prefNode.prefHasUserValue("showslider") ) this.prefNode.setBoolPref("showslider", true); if ( !this.prefNode.prefHasUserValue("alertmode") ) this.prefNode.setCharPref("alertmode", "league"); if ( !this.prefNode.prefHasUserValue("playalarm") ) this.prefNode.setBoolPref("playalarm", true); if ( !this.prefNode.prefHasUserValue("alarmtype") ) this.prefNode.setCharPref("alarmtype", "standard"); if ( !this.prefNode.prefHasUserValue("alarmfile") ) this.prefNode.setCharPref("alarmfile", ""); if ( !this.prefNode.prefHasUserValue("discretemode") ) this.prefNode.setBoolPref("discretemode", false); if ( !this.prefNode.prefHasUserValue("rotationintervall") ) this.prefNode.setIntPref("rotationintervall", 10); if ( !this.prefNode.prefHasUserValue("sliderdisplayduration") || !this.prefNode.prefHasUserValue("newdisplayduration")) { this.prefNode.setIntPref("sliderdisplayduration", 10); this.prefNode.setBoolPref("newdisplayduration", true); } if ( !this.prefNode.prefHasUserValue("rotationscope") ) this.prefNode.setCharPref("rotationscope", "all"); if ( !this.prefNode.prefHasUserValue("ET") ) this.prefNode.setCharPref("ET", "0"); if ( !this.prefNode.prefHasUserValue("menuitemsshowscores") ) this.prefNode.setBoolPref("menuitemsshowscores", true); if ( !this.prefNode.prefHasUserValue("menuitemsshowdate") ) this.prefNode.setBoolPref("menuitemsshowdate", true); if ( !this.prefNode.prefHasUserValue("menulayout") ) this.prefNode.setCharPref("menulayout", "both"); if ( !this.prefNode.prefHasUserValue("teamslisttimestamp") ) this.prefNode.setCharPref("teamslisttimestamp", ""); if ( !this.prefNode.prefHasUserValue("leagueslisttimestamp") ) this.prefNode.setCharPref("leagueslisttimestamp", ""); if ( !this.prefNode.prefHasUserValue("color.scheduled") ) this.prefNode.setCharPref("color.scheduled", "#868686"); if ( !this.prefNode.prefHasUserValue("color.active") ) this.prefNode.setCharPref("color.active", "#CC0100"); if ( !this.prefNode.prefHasUserValue("color.finished") ) this.prefNode.setCharPref("color.finished", "#868686"); if ( !this.prefNode.prefHasUserValue("iframes") ) this.prefNode.setCharPref("iframes", ""); if ( !this.prefNode.prefHasUserValue("host") ) this.prefNode.setCharPref("host", ""); // set favorite server as api host if available if ( this.prefNode.getCharPref("host") != "" ) { this.apiURL = this.prefNode.getCharPref("host"); } else { this.apiURL = this.first_apiURL; } if ( !this.prefNode.prefHasUserValue("locale") ) { var locale = "en-US"; try { var cls = '@mozilla.org/chrome/chrome-registry;1'; var service = Components.interfaces.nsIXULChromeRegistry; var locale = Components.classes[cls].getService(service).getSelectedLocale('footiefox'); } catch (e) { footiefox_d_error("Failed to detect selected locale for FootieFox: "+e); } this.prefNode.setCharPref("locale", locale); } if ( !this.prefNode.prefHasUserValue("partner") ) this.prefNode.setCharPref("partner", "1"); this.partners = document.getElementById("partners-data-bundle"); var partner = null; try { // no locale partner var partnerNum = this.prefNode.getCharPref("partner"); partner = this.partners.getString(partnerNum).split(":")[1]; } catch (e) { this.prefNode.setCharPref("partner", "1"); partner = 1; } //if ( !this.prefNode.prefHasUserValue("partner.toolbarbutton") ) // this.prefNode.setBoolPref("partner.toolbarbutton", true); if ( !this.prefNode.prefHasUserValue("partner.toolbarbuttons") ) { var buttons = ""; if ( this.prefNode.prefHasUserValue("partner.toolbarbutton") ) { if ( this.prefNode.getBoolPref("partner.toolbarbutton") ) buttons = "1"; } this.prefNode.setCharPref("partner.toolbarbuttons", buttons); } //add partner toolbar button this.addToolbarButtons(); var statusbar = document.getElementById("statusbarpanel_partner_logo"); statusbar.setAttribute("src", "chrome://footiefox/skin/"+partnerNum+"/statusbar.png"); if ( !this.prefNode.prefHasUserValue("partner.statusbarlabel") ) this.prefNode.setBoolPref("partner.statusbarlabel", true); if (!this.prefNode.getBoolPref("partner.statusbarlabel")) { var label = document.getElementById("deck_partner_logo"); label.setAttribute("hidden", true); } //check for network.http.use-cache try { var general = gDBTPrefService.getBranch("network.http."); if(!general.getBoolPref("use-cache")) { var question = "FootieFox requires HTTP caching (preference 'network.http.use-cache'), otherwise the Add-on has to be disabled. May we enable it for you?"; var enable = confirm(question); if (enable) { general.setBoolPref("use-cache", true); } else { var extensionManager = Components.classes["@mozilla.org/extensions/manager;1"]. getService(Components.interfaces.nsIExtensionManager); var extensionId = "{9fb7d178-155a-4318-9173-1a8eaaea7fe4}"; extensionManager.disableItem(extensionId); window.setTimeout(this.restartFirefox(), 500); } } } catch (e) { footiefox_d_error("check for network.http.use-cache failed: " + e); } this.myObservers = new myObservers(); this.ffTimer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer); this.ffRotationTimer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer); if ( (!this.prefNode.prefHasUserValue("tempdir")) || this.prefNode.getCharPref("tempdir")=="" ) { //determine directory for image cache var oProps = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties); this.tmpDir = (oProps.get("TmpD", Components.interfaces.nsIFile)).path; if (this.tmpDir != "") { //get slash direction var sSlash = (this.tmpDir.indexOf("\\") > -1) ? "\\" : "/"; this.tmpDir += sSlash + this.cacheFolder + sSlash; } this.prefNode.setCharPref("tempdir", this.tmpDir); } else this.tmpDir = this.prefNode.getCharPref("tempdir"); this.checkFirstExtension(); var leaguesDataBundleUpdated = document.getElementById("leagues-data-bundle-updated"); if (this.inCache("leagues.dat")) { //check if local leagues.dat valid try { leaguesDataBundleUpdated.setAttribute("src", "file://" + this.tmpDir + "leagues.dat"); var leaguesDataString = leaguesDataBundleUpdated.getString(1); //leagues.dat corrupt } catch (e) { footiefox_d_error("leagues.dat corrupt"); leaguesDataBundleUpdated.removeAttribute("src"); //reset leagueslisttimestamp so leagues.dat is being reloaded this.prefNode.setCharPref("leagueslisttimestamp", ""); } } //check if menuheader in cache and set url accordingly if (this.inCache("contextmenuheader.png")) var headerurl = "file://" + this.tmpDir + "contextmenuheader.png"; else var headerurl = this.mediaURL + this.imagesSubdirectory + "contextmenuheader.png"; var menuHeader = document.getElementById("menu_header"); menuHeader.setAttribute("src", headerurl); var teamsDataBundleUpdated = document.getElementById("teams-data-bundle-updated"); if (this.inCache("teams.dat")) { //check if local teams.dat valid try { teamsDataBundleUpdated.setAttribute("src", "file://" + this.tmpDir + "teams.dat"); var teamsDataString = teamsDataBundleUpdated.getString(11); //teams.dat corrupt } catch (e) { footiefox_d_error("teams.dat corrupt"); teamsDataBundleUpdated.removeAttribute("src"); //reset teamslisttimestamp so teams.dat is being reloaded this.prefNode.setCharPref("teamslisttimestamp", ""); } } this.checkET(); this.checkVersionUpdate(); this.applyLanguagePackage(this.prefNode.getCharPref("locale")); this.applyPartnerOverlay(); this.soundPlayer = Components.classes["@mozilla.org/sound;1"].createInstance(); this.rotationTimer = { notify: function() { var rotationscope = iFootieFox.prefNode.getCharPref("rotationscope"); if ( rotationscope == "all" ) { var num = iFootieFox.getNumberOfActiveMatches(); if ( num == 0 ) iFootieFox.displayMatch ( iFootieFox.getNextMatch() ); else iFootieFox.displayMatch ( iFootieFox.getNextActiveMatch() ); } else { var num = iFootieFox.getNumberOfActiveMatchesInLeague(); if ( num == 0 ) iFootieFox.displayMatch ( iFootieFox.getNextMatchInLeague() ); else iFootieFox.displayMatch ( iFootieFox.getNextActiveMatchInLeague() ); } } }; if ( this.prefNode.prefHasUserValue("rotation") ) { this.rotation = this.prefNode.getBoolPref("rotation"); if (this.rotation) { var rotationbox = document.getElementById("ff_popupmenu_rotate"); rotationbox.setAttribute("checked", true); this.rotation = false; this.toggleRotate(); } } this.updateLeagues = { notify: function() { iFootieFox.checkFirstExtension(); if ( !iFootieFox.firstExtension ) return; var now = new Date(); if (iFootieFox.lastUpdate != 0 && (parseInt(now.getTime()) - parseInt(iFootieFox.lastUpdate)) > 600000) { iFootieFox.lastUpdate = now.getTime(); footiefox_d_error("Browser has been hibernating ... refresh data"); setTimeout("iFootieFox.callWhatsOn(false)", 3000); return; } var leagues = iFootieFox.myScoreboard; leagueUpdateRefreshed = 0; for ( var i=0; i<leagues.length; i++ ) { var league = leagues[i]; iFootieFox.requestLeagueUpdate( league.leagueID ); } now = new Date(); iFootieFox.lastUpdate = now.getTime(); } }; //check if whatson data outdated (hibernating) this.regularWhatsOnCall = { notify: function() { if ( iFootieFox.prefNode.prefHasUserValue("logintimestamp") ) { var lastLogTimestamp = parseInt( iFootieFox.prefNode.getCharPref("logintimestamp")); var lastLog = new Date ( lastLogTimestamp ); var currentTime = new Date(); //new GMT day if ( lastLog.getUTCDate() != currentTime.getUTCDate() ) { iFootieFox.callWhatsOn(false); } } else { iFootieFox.callWhatsOn(false); } } }; this.whatsonTimer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer); this.whatsonTimer.initWithCallback(this.regularWhatsOnCall, 1000*60*30, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK); this.login(); window.addEventListener("focus", this.infocus, true); window.addEventListener("blur", this.blurred, true); }, restartFirefox: function() { var appStartup = Components.classes["@mozilla.org/toolkit/app-startup;1"]. getService(Components.interfaces.nsIAppStartup); appStartup.quit(Components.interfaces.nsIAppStartup.eForceQuit | Components.interfaces.nsIAppStartup.eRestart); }, applyLanguagePackage: function(locale) { var stringbundleDictionary = document.getElementById("stringbundle_dictionary"); //stringbundleDictionary.removeAttribute("src"); stringbundleDictionary.setAttribute("src", "chrome://footiefox/locale/"+locale+"/footiefox/footiefox.properties"); this.dictionary = document.getElementById("stringbundle_dictionary"); var countriesDataBundle = document.getElementById("countries-data-bundle"); countriesDataBundle.setAttribute("src", "chrome://footiefox/locale/"+locale+"/footiefox/countries.dat"); //document.loadOverlay("chrome://footiefox/locale/en-US/footiefox/footiefox.dtd", null); this.translate("ff_popupmenu_configurepartner"); this.translate("ff_popupmenu_matchreport1","ff.popupmenu.matchreport"); this.translate("ff_popupmenu_matchreport2","ff.popupmenu.matchreport"); this.translate("icon1menupopup_teamlocalization", "ff.popupmenu.localizeteam"); this.translate("icon2menupopup_teamlocalization", "ff.popupmenu.localizeteam"); this.translate("ff_popupmenu_rotate"); this.translate("ff_popupmenu_options"); this.translate("ff_popupmenu_about"); this.translate("ff_notice_nomatches", null, "value"); this.translate("ff_notice_noconnection"); this.translate("ff_notice_noleagues"); this.translate("ff_alerts_goal", null, "value"); }, translate: function(element_id, dictionary_id, attribute) { if (attribute == null){ attribute = "label"; } if (dictionary_id == null){ dictionary_id = element_id.replace(/_/g,"."); } try { var element = document.getElementById(element_id); element.setAttribute(attribute, this.dictionary.getString(dictionary_id)); } catch (e) { //d("Failed to translate " + element_id); } }, translateById: function (dictionary_id, original) { try { translation = this.dictionary.getString(dictionary_id); return translation; } catch (e) { return original; } }, addSearchEngine: function() { try { var appInfo = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIXULAppInfo); var versionChecker = Components.classes["@mozilla.org/xpcom/version-comparator;1"] .getService(Components.interfaces.nsIVersionComparator); //check if Firefox version is >= 2.0 if(versionChecker.compare(appInfo.version, "2.0") >= 0) { //add search engine window.external.AddSearchProvider(this.searchEngineURL); } } catch (e) { footiefox_d_error(e); return; } }, addToolbarButton: function(id) { try { if(document.getElementById("footiefox-partner-button-"+id)!=null) return; var button = document.createElement("toolbarbutton"); button.setAttribute("id", "footiefox-partner-button-"+id); button.setAttribute("context", "menupopup_partnermenupopup"); button.setAttribute("collapsed", "false"); button.setAttribute("hidden", "false"); button.setAttribute("disabled", "false"); button.setAttribute("class", "toolbarbutton-1 chromeclass-toolbar-additional footiefox-partner-button"); button.setAttribute("oncommand", "iFootieFox.partnerBannerClicked(null, 12, " + id +")"); button.setAttribute("style", "list-style-image: url(\"chrome://footiefox/skin/"+id+"/button.png\");"); var navbar = document.getElementById("nav-bar"); navbar.insertBefore(button, document.getElementById("urlbar-container")); } catch(ex) { footiefox_d_error("Failed to add FootieFox partner button "+id+" to toolbar." + ex); } }, removeToolbarButtons: function() { var partnersEnum = this.partners.strings; var index = -1; var navbar = document.getElementById("nav-bar"); while (partnersEnum.hasMoreElements()) { var element = partnersEnum.getNext(); var key = element.QueryInterface(Components.interfaces.nsIPropertyElement).key; var button = document.getElementById("footiefox-partner-button-" + key); try { if (button!= null) navbar.removeChild(button); } catch (e) { footiefox_d_error(e); } } }, addToolbarButtons: function() { this.removeToolbarButtons(); var buttonsString = this.prefNode.getCharPref("partner.toolbarbuttons"); var buttonsArray = buttonsString.split(":"); for (var i=0;i<buttonsArray.length;i++) { var partnerNum = buttonsArray[i]; if(isNaN(parseInt(partnerNum))) continue; this.addToolbarButton(buttonsArray[i]); } }, checkVersionUpdate: function() { var field = "version"; var extensionId = "{9fb7d178-155a-4318-9173-1a8eaaea7fe4}"; var rdfs = Components.classes["@mozilla.org/rdf/rdf-service;1"] .getService(Components.interfaces.nsIRDFService); var extensionDS = Components.classes["@mozilla.org/extensions/manager;1"] .getService(Components.interfaces.nsIExtensionManager).datasource; var extension = rdfs.GetResource("urn:mozilla:item:" + extensionId); var fieldArc = rdfs.GetResource( "http://www.mozilla.org/2004/em-rdf#" + field); var valueLiteral = extensionDS.GetTarget(extension, fieldArc, true); // value contains the string var version = valueLiteral.QueryInterface(Components.interfaces.nsIRDFLiteral).Value; var oldversion = null; try { oldversion = this.prefNode.getCharPref("version"); } catch (e) {} var eula = null; if (this.prefNode.prefHasUserValue("eula")) { eula = this.prefNode.getCharPref("eula"); } //updated! if (!this.prefNode.prefHasUserValue("version") || oldversion != version || eula!="accepted") { this.prefNode.setCharPref("version", version); var language = "en"; var gDBTPrefService = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService); try { var general = gDBTPrefService.getBranch("general.useragent."); var loc = general.getCharPref("locale"); if (loc =="de-DE" || loc=="de") language = "de"; } catch(e) {}; //open website on version history var browser = document.getElementById("content"); var tab = browser.addTab("http://"+language+".footiefox.com/pages/update/"+version); browser.selectedTab = tab; //update from 1.x to 2.x if ( oldversion == null || (oldversion.split(".")[0]=="1" && version.split(".")[0]=="2" || eula!="accepted" )) { //remove old IDs iFootieFox.prefNode.setCharPref("leaguestofollow", ""); iFootieFox.prefNode.setCharPref("teamstofollow", ""); //openDialog('chrome://footiefox/content/wizard.xul', 'wizard', 'chrome,dialog,modal,centerscreen'); wiz = window.openDialog('chrome://footiefox/content/wizard.xul', 'wizard', 'chrome,dialog,centerscreen'); window.setTimeout(iFootieFox.focusWizard, 1000); } else { if (!this.isSearchEngineInstalled()) this.addSearchEngine(); } } }, focusWizard: function() { wiz.focus(); }, isSearchEngineInstalled: function () { var searchService = Cc["@mozilla.org/browser/search-service;1"].getService(Ci.nsIBrowserSearchService); var engineName = searchService.currentEngine.name; if (searchService.getEngineByName("FootieFox") == null) return false; else return true; }, showSlider: function() { var goalwin = document.getElementById("ff_alert"); goalwin.setAttribute("hidden", "false"); var ad = iFootieFox.scoreAd; var h = 108; var w = 200; //adjust size for ad if (ad != null) { h += ad.height; w = ad.width; } var style = "height:" + goalAlertHeight +"px;width:"+w+"px;z-Index:300;overflow-x:auto;overflow-y:hidden;"; goalwin.setAttribute("style", style); goalAlertHeight = goalAlertHeight + 1; if (goalAlertHeight < h ) window.setTimeout(iFootieFox.showSlider,20); else { goalAlertHeight = 0; var displayduration = iFootieFox.prefNode.getIntPref("sliderdisplayduration"); window.setTimeout(iFootieFox.hideSlider,displayduration*1000); } }, hideSlider: function() { var goalwin = document.getElementById("ff_alert"); goalwin.setAttribute("hidden", "false"); var ad = iFootieFox.scoreAd; var h = 108; var w = 200; //adjust size for ad if (ad != null) { h += ad.height; w = ad.width; } var style = "height:"+parseInt(h-goalAlertHeight)+"px;width:" + w + "px;overflow-x:auto;overflow-y:hidden;"; goalwin.setAttribute("style", style); goalAlertHeight = goalAlertHeight + 1; if (goalAlertHeight < h ) window.setTimeout(iFootieFox.hideSlider,20); else { footiefox_d_message("finally hidden"); goalAlertHeight = 0; goalwin.setAttribute("hidden", "true"); FootieFoxSliderAction = false; iFootieFox.displayGoalAlert(); } }, infocus: function(event) { windowfocused = true; }, blurred: function(event) { windowfocused = false; }, displayGoalAlert: function() { footiefox_di_message("displayGoalAlert"); if ( sliders.length == 0 || sliders == null || FootieFoxSliderAction == true ) { footiefox_d_message("FootieFoxSliderAction: " + FootieFoxSliderAction); return; } FootieFoxSliderAction = true; var matchDiff = sliders.shift(); var matchid = matchDiff.matchId; var scoringMatch = this.getMatch( matchid ); var teamid = matchDiff.teamId; var teamtitle = ""; if ( scoringMatch.team1Id == teamid ) teamtitle = scoringMatch.team1Title; if ( scoringMatch.team2Id == teamid ) teamtitle = scoringMatch.team2Title; this.checkFirstExtension(); if ( this.firstExtension ) { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); var maximizedlist = observerService.enumerateObservers("footiefoxWindowMaximized"); //remove old "maximized" observers while ( maximizedlist.hasMoreElements() ) { var observer = maximizedlist.getNext(); observerService.removeObserver(observer, "footiefoxWindowMaximized"); } //all windows make selftest on maximized status Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService) .notifyObservers(null, "footiefoxMaximized", ""); maximizedlist = observerService.enumerateObservers("footiefoxWindowMaximized"); if ( maximizedlist.hasMoreElements() ) { //new sliders Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService) .notifyObservers(null, "footiefoxGoalAlert", teamid + ";" + teamtitle + ";" + matchid + ";" + scoringMatch.team1Score + ";" + scoringMatch.team2Score + ";" + scoringMatch.phase); } else { //old sliders this.goalAlert(teamid, teamtitle); } } }, determineAppropriateAd: function (parameters) { var teamid = parameters.split(";")[0]; var teamtitle = parameters.split(";")[1]; var matchid = parameters.split(";")[2]; var match = this.getMatch(matchid); var league = this.getLeagueByMatch( match ); var leagueId = league.leagueID; var country = this.getCountryByLeague( leagueId ); var gDBTPrefService = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService); var locale = this.prefNode.getCharPref("locale"); //find appropriate ad here var listOfAds = new Array(); //ads for scoring team have highest priority for ( var i=0; i<this.scoreAds.length; i++ ) { var currentAd = this.scoreAds[i]; if ( (currentAd.team_id == teamid) && (currentAd.locale == locale || currentAd.locale == "xx-XX") ) { listOfAds.push(currentAd); continue; } } //league-speficic ads come second if (listOfAds.length == 0) { for ( var i=0; i<this.scoreAds.length; i++ ) { var currentAd = this.scoreAds[i]; if ( (currentAd.league_id == leagueId) && (currentAd.locale == locale || currentAd.locale == "xx-XX") ) { listOfAds.push(currentAd); continue; } } } //country related ads if (listOfAds.length == 0) { for ( var i=0; i<this.scoreAds.length; i++ ) { var currentAd = this.scoreAds[i]; if ( (currentAd.country_id == country) && (currentAd.locale == locale || currentAd.locale == "xx-XX") ) { listOfAds.push(currentAd); continue; } } } //ads for language target group /*if (listOfAds.length == 0) { for ( var i=0; i<this.scoreAds.length; i++ ) { var currentAd = this.scoreAds[i]; if ( currentAd.locale == locale || currentAd.locale == "xx-XX" ) { alert("leagueid: "+currentAd.locale +"=="+ locale ); listOfAds.push(currentAd); continue; } } }*/ //at least one appropriate ad found var finalAds = new Array(); if ( listOfAds.length > 0 ) { var prio = -1; for ( var i=0; i<listOfAds.length; i++ ) { var currentAd = listOfAds[i]; if (currentAd.priority == prio) { finalAds.push(currentAd); } if (currentAd.priority > prio) { prio = currentAd.priority; finalAds = new Array(); finalAds.push(currentAd); } } var index = Math.random(); index *= finalAds.length; index = Math.ceil(index); this.scoreAd = finalAds[index-1]; height = this.scoreAd.height; } }, updateAlertSlider: function(parameters) { var teamid = parameters.split(";")[0]; var teamtitle = parameters.split(";")[1]; var matchid = parameters.split(";")[2]; var score1 = parameters.split(";")[3]; var score2 = parameters.split(";")[4]; var phase = parameters.split(";")[5]; var match = this.getMatch(matchid); var league = this.getLeagueByMatch ( match ); var leagueid = league.leagueID; if (match != -1) { var ff_alert_score1 = document.getElementById("ff_alert_score1"); var ff_alert_score2 = document.getElementById("ff_alert_score2"); var ff_alert_phase = document.getElementById("ff_alert_phase"); ff_alert_score1.setAttribute("value", score1); ff_alert_score2.setAttribute("value", score2); if (phase && phase != 'undefined' && phase != 'null') ff_alert_phase.setAttribute("value", phase); else ff_alert_phase.setAttribute("value", ""); if (teamid == match.team1Id) { ff_alert_score1.setAttribute("style", "font-size:18px;"); ff_alert_score2.setAttribute("style", "margin-top:3px;"); } if (teamid == match.team2Id) { ff_alert_score2.setAttribute("style", "font-size:18px;"); ff_alert_score1.setAttribute("style", "margin-top:3px;"); } match.team1Score = score1; match.team2Score = score2; match.phase = phase; } var slider = document.getElementById("ff_alert"); slider.setAttribute("hidden", "false"); var logo = document.getElementById("ff_alert_team_logo"); if (this.inCache(teamid + "big.png")) var flagURL = "file://" + this.tmpDir + teamid + "big.png"; else var flagURL = this.mediaURL + this.imagesSubdirectory + teamid + "big.png"; logo.setAttribute("src", flagURL); var title = document.getElementById("ff_alert_team_title"); title.setAttribute("value", teamtitle); var vbox = document.getElementById("ff_alert_vbox"); var url1 = this.redirectURL +"redirect/" + this.prefNode.getCharPref("partner") + "/6/" + matchid + "/" + this.prefNode.getCharPref("locale") + "/" + teamid+"?client_id="+this.getSerial(); vbox.setAttribute("onclick", "iFootieFox.visitWebpage(\""+ url1 +"\")"); var url2 = this.redirectURL +"redirect/" + this.prefNode.getCharPref("partner") + "/7/" + matchid + "/" + this.prefNode.getCharPref("locale") + "/" + teamid+"?client_id="+this.getSerial(); var alert_partner = document.getElementById("ff_alert_partner"); alert_partner.setAttribute("onclick", "iFootieFox.visitWebpage(\""+ url2 +"\")"); // score ad this.scoreAd = null; this.determineAppropriateAd(parameters); var ad = this.scoreAd; var vbox = document.getElementById("ff_alert"); var h = 108; var w = 200; var iframe = document.getElementById("ff_alert_banner"); //adjust size for ad if (this.scoreAd != null) { h = 108 + this.scoreAd.height; w = this.scoreAd.width; iframe.setAttribute("src", ad.url); iframe.setAttribute("style", "overflow:hidden;height:" + ad.height +"px;width:" + ad.width + "px;"); } else { iframe.setAttribute("style", "overflow:hidden;height:108px;width:200px;"); } vbox.setAttribute("style", "height:" + h +"px;width:" + w + "px;"); }, hideGoalAlert: function() { var slider = document.getElementById("ff_alert"); slider.setAttribute("hidden", "true"); }, displayIFrame: function(id, url, w, h) { try { var idsstring = this.prefNode.getCharPref("iframes"); var ids = idsstring.split(","); if (!inArray(id, ids)) { //append new id at beginning ids.unshift(id); var size = ids.length; if (size > 5) size = 5; var iframesstring = ""; for (var i=0;i<size;i++) iframesstring += ids[i] + ","; this.prefNode.setCharPref("iframes", iframesstring); var banner = document.getElementById("ff_notification_banner"); banner.setAttribute("hidden", "false"); var iframe = document.getElementById("ff_iframe_banner"); iframe.setAttribute("src", url); var style= "position:absolute;left:0px;border:none;overflow:hidden;width:"+ w +"px;height:"+ h +"px;"; iframe.setAttribute("style", style); } } catch (e) { footiefox_d_error(e); } }, closeBanner: function() { var banner = document.getElementById("ff_notification_banner"); banner.setAttribute("hidden", "true"); }, stopNotification: function() { var checkbox = document.getElementById("ff_notification_checkbox"); if (checkbox.checked) { this.prefNode.setCharPref("latestversion", this.latestmajor + "." + this.latestminor); } }, updateMyLeagues: function () { this.myLeagues = new Array(); var leaguesToFollow = this.prefNode.getCharPref("leaguestofollow"); if (leaguesToFollow!="") { leaguesToFollow = leaguesToFollow.split(","); for (var x=0; x<leaguesToFollow.length-1; x++) { if ( this.isNumber(leaguesToFollow[x]) ) this.myLeagues.push(leaguesToFollow[x]); } } }, isNumber: function(s){ if (s.length == 0) return false; var i; for (i = 0; i < s.length; i++) { // check if current character is number var c = s.charAt(i); if (((c < "0") || (c > "9"))) return false; if ( s == " " ) return false; } return true; }, updateMyTeams: function () { this.myTeams = new Array(); var teamsToFollow = this.prefNode.getCharPref("teamstofollow"); if (teamsToFollow!="") { teamsToFollow = teamsToFollow.split(","); for (var x=0; x<teamsToFollow.length-1; x++) { this.myTeams.push(teamsToFollow[x]); } } }, getNumberOfActiveMatches: function () { var leagues = this.myScoreboard; var activeMatches = 0; for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { if (matches[y].status == "active") activeMatches += 1; } } return activeMatches; }, getNumberOfActiveMatchesInLeague: function () { var leagues = this.myScoreboard; var league = this.getLeagueByMatch ( this.selectedMatch ); var matches = league.matches; var activeMatches = 0; for ( var x = 0; x < matches.length; x++ ) { var match = league.matches[x]; if (match.status == "active") activeMatches += 1; } return activeMatches; }, getNextMatch: function () { var leagues = this.myScoreboard; var currentMatch = false; for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if ( currentMatch && match.team1Id > 0 ) return match; var id = match.matchID; if ( id == this.selectedMatch.matchID ) currentMatch = true; } } //current match last of list, return very first which is no placeholder for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if ( match.team1Id > 0 ) return match; } } return null; }, getNextActiveMatch: function () { var leagues = this.myScoreboard; var currentMatch = false; for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if ( currentMatch && match.team1Id > 0 && match.status == "active") return match; var id = match.matchID; if ( id == this.selectedMatch.matchID ) currentMatch = true; } } //current match last of list, return very first which is no placeholder for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if ( match.team1Id > 0 && match.status == "active") return match; } } return null; }, getNextMatchInLeague: function () { var leagues = this.myScoreboard; var league = this.getLeagueByMatch ( this.selectedMatch ); var matches = league.matches; var currentMatch = false; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if ( currentMatch ) return match; var id = match.matchID; if ( id == this.selectedMatch.matchID ) currentMatch = true; } //current match last of current league list for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if ( match.team1Id > 0 ) return match; } return null; }, getNextActiveMatchInLeague: function () { var leagues = this.myScoreboard; var league = this.getLeagueByMatch ( this.selectedMatch ); var matches = league.matches; var currentMatch = false; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if ( currentMatch && match.status == "active") return match; var id = match.matchID; if ( id == this.selectedMatch.matchID ) currentMatch = true; } //current match last of current league list for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if ( match.team1Id > 0 && match.status == "active") return match; } return null; }, getMatch: function ( matchID ) { var leagues = this.myScoreboard; for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; var id = match.matchID; if ( matchID == id ) return match; } } //match not found return -1; }, getLeagueByID: function ( leagueID ) { var leagues = this.myScoreboard; for ( var x = 0; x < leagues.length; x++ ) { var league = leagues[x]; var currentLeagueID = league.leagueID; if ( currentLeagueID == leagueID ) return league; } return -1; }, getMatchesByLeagueId: function (leagueId) { var leagues = this.myScoreboard; for ( var x = 0; x < leagues.length; x++ ) { var currentLeagueId = leagues[x].leagueID; if ( currentLeagueId == leagueId ) return leagues[x].matches; } return null; }, getLeagueByMatch: function ( match ) { var leagues = this.myScoreboard; for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var currentmatch = matches[y]; var id = currentmatch.matchID; if ( match.matchID == id ) return leagues[x]; } } //match not found return -1; }, getCountryByLeague: function ( leagueId ) { var leaguesDataBundle = this.getCurrentLeaguesDataBundle(); var country = -1; try { var leagueString = leaguesDataBundle.getString(leagueId); country = leagueString.split(":")[2]; } catch (e) { footiefox_d_error("getCountryByLeague" + e); } return country; }, displayMatch: function( match ) { //d("displayMatch: " + match.matchID); if (match == null) { match = this.getFirstMatch(); this.selectedMatch = match; } if ( match == null || match.team1Id < 0 ) return; this.switchDisplay("match"); this.selectedMatch = match; //score label var score = document.getElementById("statusbarpanel_score"); var score1 = match.team1Score; var score2 = match.team2Score; var phase = ""; if (match.phase != null && match.phase != "") { phase = " ("+match.phase+")"; } if (match.status != "scheduled") score.setAttribute("value", score1 + ":" + score2 + phase); else score.setAttribute("value", "-:-"); score.setAttribute("status", match.status); if (match.status=="scheduled") score.setAttribute("style","cursor: pointer;color:"+this.prefNode.getCharPref("color.scheduled")); if (match.status=="active") score.setAttribute("style","cursor: pointer;color:"+this.prefNode.getCharPref("color.active")); if (match.status=="finished") score.setAttribute("style","cursor: pointer;color:"+this.prefNode.getCharPref("color.finished")); //flags var flag1 = document.getElementById("statusbarpanel_flag1"); var flag2 = document.getElementById("statusbarpanel_flag2"); var teamID1 = match.team1Id; var teamID2 = match.team2Id; //check if logos are in cache and set urls accordingly if (this.inCache(teamID1 + ".png")) var flagURL1 = "file://" + this.tmpDir + teamID1 + ".png"; else var flagURL1 = this.mediaURL + this.imagesSubdirectory + teamID1 + ".png"; if (this.inCache(teamID2 + ".png")) var flagURL2 = "file://" + this.tmpDir + teamID2 + ".png"; else var flagURL2 = this.mediaURL + this.imagesSubdirectory + teamID2 + ".png"; flag1.setAttribute("src", flagURL1); flag2.setAttribute("src", flagURL2); var tooltip1 = match.team1Title; var tooltip2 = match.team2Title; flag1.setAttribute("tooltiptext", tooltip1); flag2.setAttribute("tooltiptext", tooltip2); var moreon = null; try { moreon = this.dictionary.getString("ff.popupmenu.teaminfo"); } catch (e) { moreon ="More on"; } var icon1menupopup_team = document.getElementById("icon1menupopup_team"); icon1menupopup_team.setAttribute("label", moreon +" '"+ match.team1Title+"'"); var icon2menupopup_team = document.getElementById("icon2menupopup_team"); icon2menupopup_team.setAttribute("label", moreon +" '"+ match.team2Title+"'"); var icon1menupopup_teamlocalization = document.getElementById("icon1menupopup_teamlocalization"); var icon2menupopup_teamlocalization = document.getElementById("icon2menupopup_teamlocalization"); if (this.prefNode.getCharPref("locale") == "de-DE") { icon1menupopup_teamlocalization.setAttribute("collapsed","true"); icon1menupopup_teamlocalization.setAttribute("hidden","true"); icon2menupopup_teamlocalization.setAttribute("collapsed","true"); icon2menupopup_teamlocalization.setAttribute("hidden","true"); } else { icon1menupopup_teamlocalization.setAttribute("collapsed","false"); icon1menupopup_teamlocalization.setAttribute("hidden","false"); icon2menupopup_teamlocalization.setAttribute("collapsed","false"); icon2menupopup_teamlocalization.setAttribute("hidden","false"); } var currentleague = this.getLeagueByMatch(match); var ff_popupmenu_matchreport1 = document.getElementById("ff_popupmenu_matchreport1"); var ff_popupmenu_matchreport2 = document.getElementById("ff_popupmenu_matchreport2"); var partner = this.checkForLeaguePartner(currentleague.leagueID); var statusbar = document.getElementById("statusbarpanel_partner_logo"); if (partner==-1) { partner = this.prefNode.getCharPref("partner"); } statusbar.setAttribute("src", "chrome://footiefox/skin/"+partner+"/statusbar.png"); statusbar.removeAttribute("onclick"); statusbar.setAttribute("onclick", "iFootieFox.bannerClicked(event, "+partner+")"); flag1.removeAttribute("onclick"); flag1.setAttribute("onclick", "iFootieFox.icon1Clicked(event,"+partner+")"); flag2.removeAttribute("onclick"); flag2.setAttribute("onclick", "iFootieFox.icon2Clicked(event,"+partner+")"); ff_popupmenu_matchreport1.removeAttribute("oncommand"); ff_popupmenu_matchreport1.setAttribute("oncommand","iFootieFox.contextMenuReportClicked1("+partner+");"); ff_popupmenu_matchreport2.removeAttribute("oncommand"); ff_popupmenu_matchreport2.setAttribute("oncommand","iFootieFox.contextMenuReportClicked2("+partner+");"); var score = document.getElementById("statusbarpanel_score"); score.removeAttribute("tooltiptext"); }, checkForLeaguePartner: function (leagueid) { var partnersEnum = this.partners.strings; var index = -1; while (partnersEnum.hasMoreElements()) { try { var element = partnersEnum.getNext(); var key = element.QueryInterface(Components.interfaces.nsIPropertyElement).key; var value = element.QueryInterface(Components.interfaces.nsIPropertyElement).value; try { var leaguesValue = value.split(":")[2]; var leagues = leaguesValue.split(","); for (var i=0;i<leagues.length;i++) { var league = leagues[i]; if (league == leagueid) return key; } } catch (e) { continue; } } catch(ex){ footiefox_d_error(ex); continue; } } try { return this.prefNode.getCharPref("partner"); } catch (e) { footiefox_d_error("checkForLeaguePartner: "+ e); } return -1; }, inCache: function (filename) { if (this.tmpDir == "") return false; var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(this.tmpDir + filename); if (file.exists()) return true; else return false; }, updateData: function (matchDiffs, awake) { //footiefox_d_message("updateData"); var delay = 0; var goal = false; for (var x=0; x<matchDiffs.length; x++) { var matchDiff = matchDiffs[x]; var matchid = matchDiff.matchId; var currentmatchid = this.selectedMatch.matchID; var currentleague = this.getLeagueByMatch(this.selectedMatch); var currentleagueid = currentleague.leagueID; var match = this.getMatch( matchid ); var league = this.getLeagueByMatch(match); var leagueid = league.leagueID; var alertmode = this.prefNode.getCharPref("alertmode"); var showslider = this.prefNode.getBoolPref("showslider"); this.checkFirstExtension(); if ( this.firstExtension && showslider && !awake ) if ( (alertmode == "all") || (alertmode == "game" && currentmatchid == matchid ) || (alertmode == "league" && currentleagueid == leagueid ) ) { if (matchDiff.teamId != null) { sliders.push(matchDiff); goal = true; } } leagueIndex = this.getLeagueIndex(leagueid); matchIndex = this.getMatchIndex(leagueid, matchid); //update scoreboard this.myScoreboard[leagueIndex].matches[matchIndex].status = matchDiff.status; this.myScoreboard[leagueIndex].matches[matchIndex].team1Score = matchDiff.team1Score; this.myScoreboard[leagueIndex].matches[matchIndex].team2Score = matchDiff.team2Score; this.myScoreboard[leagueIndex].matches[matchIndex].phase = matchDiff.phase; } //play sound only once, even if there are a couple of goals with this update if (goal == true && this.prefNode.getBoolPref("playalarm") && !awake) { var soundfileURL = this.prefNode.getCharPref("alarmfile"); playAlarmSound(soundfileURL); } this.displayMatch(this.selectedMatch); if (sliders.length > 0) { this.displayGoalAlert(); } }, getMatchPhase: function (id) { switch (id) { case 3: return this.translateById("ff.notice.overtime", "AET"); break; case 4: return this.translateById("ff.notice.overtime", "AET"); break; case 5: return this.translateById("ff.notice.penalties", "Pens"); break; default: return ""; } }, getLeagueIndex: function (leagueid) { try { for ( var i=0; i<this.myScoreboard.length; i++ ) { if (this.myScoreboard[i].leagueID == leagueid) return i; } } catch (e) { footiefox_d_error("getLeagueIndex: "+ e); return -1; } return null; }, getMatchIndex: function (leagueid, matchid) { try { league = this.getLeagueByID(leagueid); for ( var i=0; i<league.matches.length; i++ ) if (league.matches[i].matchID == matchid) return i; } catch (e) { footiefox_d_error("getMatchIndex: "+ e); return -1; } return null; }, checkFirstExtension: function () { //detect if maybe first extension was destroyed var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); var extensionslist = observerService.enumerateObservers("footiefoxExtension"); //no footiefox registered yet - this is the "first extension" if ( !extensionslist.hasMoreElements() ) { this.firstExtension = true; observerService.addObserver(this, "footiefoxExtension", false); } }, //checks if this window is visible checkWindowMaximized: function () { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); var maximizedlist = observerService.enumerateObservers("footiefoxWindowMaximized"); //this window is visible footiefox_d_message("this windows has focus:"+windowfocused); if ( windowfocused ) if ( !maximizedlist.hasMoreElements() ) { observerService.addObserver(this, "footiefoxWindowMaximized", false); } }, goalAlert: function (teamId, teamTitle) { FootieFoxSliderAction = false; try { var alertService = Components.classes["@mozilla.org/alerts-service;1"].getService(Components.interfaces.nsIAlertsService); var teamString = teamTitle; if (this.inCache(teamId + "big.png")) var url = "file://" + this.tmpDir + teamId + "big.png"; else var url = this.mediaURL + this.imagesSubdirectory + teamId + "big.png"; var slogan = "FOOTIEFOX"; try { slogan = this.dictionary.getString("ff.alerts.goal") + " "; } catch (e) { footiefox_d_error("goalAlert"+e); } var listener = { observe: function(subject, topic, data) { iFootieFox.displayGoalAlert(); } } alertService.showAlertNotification(url, slogan, teamString, false, "", listener); } catch (e) { footiefox_d_error(e);} }, messageAlert: function () { var url = this.messages[ this.lastMessage ].url; var linkurl = this.messages[ this.lastMessage ].linkurl; var linktext = this.messages[ this.lastMessage ].linktext; this.lastMessage +=1; try { var alertService = Components.classes["@mozilla.org/alerts-service;1"].getService(Components.interfaces.nsIAlertsService); var fileName = url.substring(url.lastIndexOf('/')+1, url.length); if (this.inCache(fileName)) var url = "file://" + this.tmpDir + "/" + fileName; alertService.showAlertNotification(url, "", linktext, true, "", this.myObservers); } catch (e) {} }, removeMenu: function() { //d("removeMenu"); //remove dynamic menu items var menupopup_mainmenupopup = document.getElementById("menupopup_mainmenupopup"); var menuitems = null; try { menuitems = menupopup_mainmenupopup.getElementsByTagName("menu"); } catch (e) {} while ( menuitems.length > 0 ) { menuitems = menupopup_mainmenupopup.getElementsByTagName("menu"); var child = menuitems[0]; menupopup_mainmenupopup.removeChild(child); } }, highlightMenuItem: function(element) { element.setAttribute("style", "background:#0A246A;color:white"); var labels = element.getElementsByTagName("label"); for (var x = 0; x < labels.length; x++) { var label = labels[x]; label.setAttribute("style", "color:white"); } }, unhighlightMenuItem: function(element) { element.removeAttribute("style"); var labels = element.getElementsByTagName("label"); for (var x = 0; x < labels.length; x++) { var label = labels[x]; label.setAttribute("style", "color:black"); if (label.getAttribute("status")=="scheduled") { label.setAttribute("style","color:"+this.prefNode.getCharPref("color.scheduled")); } if (label.getAttribute("status")=="active") { label.setAttribute("style","color:"+this.prefNode.getCharPref("color.active")); } if (label.getAttribute("status")=="finished") { label.setAttribute("style","color:"+this.prefNode.getCharPref("color.finished")); } } }, hideMenu: function() { var mainPopupSet = document.getElementById("menupopup_mainmenupopup"); mainPopupSet.hidePopup(); }, getCurrentLeaguesDataBundle: function() { var leaguesDataBundleUpdated = document.getElementById("leagues-data-bundle-updated"); var leaguesDataBundle = null; //updated leagues.dat valid if ( leaguesDataBundleUpdated.hasAttribute("src") ) leaguesDataBundle = leaguesDataBundleUpdated; //updated leagues.dat corrupt, take inbuilt leagues.dat else leaguesDataBundle = document.getElementById("leagues-data-bundle"); return leaguesDataBundle; }, buildMenu: function() { footiefox_d_message("buildMenu"); // don't rebuild when menu is currently shown if (this.menu_visible) { return; } //clear old menu entries this.removeMenu(); var leaguesDataBundle = this.getCurrentLeaguesDataBundle(); for (var x=0; x < this.myScoreboard.length; x++) { var league = this.myScoreboard[x]; //////////menuitem for league title///////////// var mainPopupSet = document.getElementById("menupopup_mainmenupopup"); //append menu right after creation! var menu = document.createElement("menu"); mainPopupSet.appendChild(menu); mainPopupSet.setAttribute("onpopupshown", "iFootieFox.menu_visible = true;"); mainPopupSet.setAttribute("onpopuphidden", "iFootieFox.menu_visible = false;"); var countryshort = this.getLeagueCountryShort(league.leagueID); if ( countryshort != "" ) countryshort = " (" + countryshort + ")"; var label = this.getLocalLeagueTitle(league.leagueID) + countryshort; menu.setAttribute("label", label ); menu.setAttribute("id", league.leagueID); var menupopup = document.createElement("menupopup"); menupopup.setAttribute("id", league.leagueID); menupopup.setAttribute("class", "footiefox_match_list"); menu.appendChild(menupopup); /////////entry for each match//////////// var menulayout = this.prefNode.getCharPref("menulayout"); var showscores = this.prefNode.getBoolPref("menuitemsshowscores"); var showdate = this.prefNode.getBoolPref("menuitemsshowdate"); var olddate = null; var games = league.matches; var groups = new Array(); var groupItems = new Array(); for (var i=0; i<games.length; i++) { var game = games[i]; var group_id = 0; if (typeof(game.tournament_group) != 'undefined') group_id = game.tournament_group; var group = null; for ( var j=0; j<groups.length; j++ ) { var current_group = groups[j]; if (current_group.id == group_id) { group = current_group; break; } } if (group) { group.games.push(game); } else { group = new Object(); group.id = group_id; group.games = new Array(); group.games.push(game); groups.push(group); } } var groupend = true; for (var zz = 0; zz < groups.length; zz++) { var scoreboard_vbox = document.createElement("vbox");; var group = groups[zz]; var groupmenupopup = null; var games = group.games; for (var y = 0; y < games.length; y++) { var game = games[y]; var hbox = document.createElement("hbox"); if (showdate) { var date = new Date(game.startTime); var localdate = ""; if (date != null) localdate = date.toLocaleDateString(); var timebox = document.createElement("vbox"); timebox.setAttribute("pack", "center"); var timelabel = document.createElement("label"); var timestring = date.toLocaleTimeString(); timestring = timestring.replace(/:\d\d([^:]|$)/, " "); timelabel.setAttribute("value", timestring); timelabel.setAttribute("id", "kickofftime"); timebox.appendChild(timelabel); hbox.appendChild(timebox); //skip in case date exists already var datenew = true; try { var elements = scoreboard_vbox.getElementsByTagName("label"); for (var z=0; z<elements.length; z++) if (elements[z].getAttribute("value") == localdate) { datenew = false; break; } } catch(e) {footiefox_d_error("buildMenu"+e);} if (datenew && date != null) { var datebox = document.createElement("hbox"); datebox.setAttribute("id", "datebox"); var datelabel = document.createElement("label"); datelabel.setAttribute("value", localdate); datelabel.setAttribute("id", "kickoffdate"); datebox.appendChild(datelabel); scoreboard_vbox.appendChild(datebox); var menuseparator = document.createElement("menuseparator"); menuseparator.setAttribute("id", "dateunderline"); scoreboard_vbox.appendChild( menuseparator ); } } var teamtitle1 = game.team1Title; var teamtitle2 = game.team2Title var score1 = game.team1Score; var score2 = game.team2Score; if ( game.status == "scheduled" ) { score1 = "-"; score2 = "-"; } hbox.setAttribute ("id", game.matchID ); hbox.setAttribute ("onmouseover", "iFootieFox.highlightMenuItem(this);"); hbox.setAttribute ("onmouseout", "iFootieFox.unhighlightMenuItem(this);"); hbox.setAttribute ("onclick", "iFootieFox.displayMatch(iFootieFox.getMatch(this.id));iFootieFox.hideMenu();"); hbox.setAttribute ("pack", "center"); var hboxscore = document.createElement("hbox"); hboxscore.setAttribute ("pack", "center"); hboxscore.setAttribute ("id", "score"); hboxscore.setAttribute ("status", game.status ); hboxscore.setAttribute ("style", "width:45px;"); var vboxscore = document.createElement("vbox"); vboxscore.setAttribute("style", "width:25px"); vboxscore.setAttribute("pack", "center"); vboxscore.setAttribute("align", "right"); var labelscore = document.createElement("label"); labelscore.setAttribute("style", "margin:0px;width:20px;"); if (game.status=="scheduled") { labelscore.setAttribute("style","color:"+this.prefNode.getCharPref("color.scheduled")); labelscore.setAttribute("status", "scheduled"); } if (game.status=="active") { labelscore.setAttribute("style","color:"+this.prefNode.getCharPref("color.active")); labelscore.setAttribute("status", "active"); } if (game.status=="finished") { labelscore.setAttribute("style","color:"+this.prefNode.getCharPref("color.finished")); labelscore.setAttribute("status", "finished"); } labelscore.setAttribute("pack", "center"); var phase = " "; if (game.phase) { phase = " ("+game.phase+")"; } var scorestring = ""; var score1length = 0; var score2length = 0; try { score1length = score1.toString().length; } catch (e) {} if (score1length < 2) scorestring += " "; scorestring += score1 + ":" + score2 + phase; labelscore.setAttribute("value", scorestring); vboxscore.appendChild( labelscore ); hboxscore.appendChild (vboxscore); var vboxvs = document.createElement("vbox"); vboxvs.setAttribute ("pack", "center"); vboxvs.setAttribute ("style", "max-width: 50px"); var labelvs = document.createElement("label"); labelvs.setAttribute("value", "vs."); labelvs.setAttribute("id", "vs"); vboxvs.appendChild (labelvs); var vboxlabelteamtitle1 = document.createElement("vbox"); var labelteamtitle1 = document.createElement("label"); labelteamtitle1.setAttribute("value", teamtitle1); labelteamtitle1.setAttribute("id", "teamtitle"); vboxlabelteamtitle1.setAttribute("pack", "center"); vboxlabelteamtitle1.setAttribute("flex", "2"); vboxlabelteamtitle1.appendChild(labelteamtitle1); var vboxlabelteamtitle2 = document.createElement("vbox"); var labelteamtitle2 = document.createElement("label"); labelteamtitle2.setAttribute("value", teamtitle2); labelteamtitle2.setAttribute("id", "teamtitle"); vboxlabelteamtitle2.setAttribute("pack", "center"); vboxlabelteamtitle2.setAttribute("flex", "2"); vboxlabelteamtitle2.appendChild(labelteamtitle2); var img1 = document.createElement("image"); if (this.inCache(game.team1Id + ".png")) var src1 = "file://" + this.tmpDir + game.team1Id + ".png"; else var src1 = this.mediaURL + this.imagesSubdirectory + game.team1Id + ".png"; img1.setAttribute("src", src1); img1.setAttribute("width", "30px"); if ( menulayout == "logos" ) img1.setAttribute("tooltiptext", teamtitle1); var img2 = document.createElement("image"); if (this.inCache(game.team2Id + ".png")) var src2 = "file://" + this.tmpDir + game.team2Id + ".png"; else var src2 = this.mediaURL + this.imagesSubdirectory + game.team2Id + ".png"; img2.setAttribute("src", src2); img2.setAttribute("width", "30px"); if ( menulayout == "logos" ) img2.setAttribute("tooltiptext", teamtitle2); if ( menulayout != "titles" ) hbox.appendChild (img1); if ( menulayout != "logos" ) hbox.appendChild (vboxlabelteamtitle1); if ( showscores ) { hbox.appendChild (hboxscore); } else { hbox.appendChild (vboxvs); } if ( menulayout != "logos" ) hbox.appendChild (vboxlabelteamtitle2); if ( menulayout != "titles" ) hbox.appendChild (img2); scoreboard_vbox.appendChild(hbox); if ( y < games.length - 1 ) { var spacerbox = document.createElement("hbox"); var label = document.createElement("label"); spacerbox.appendChild (label); scoreboard_vbox.appendChild(spacerbox); } } if (groups.length > 1) { var groupmenu = document.createElement("menu"); //menupopup.appendChild(groupmenu); groupmenu.setAttribute("id", group.id); //do some translation var glabel = group.id.replace(/Gruppe/,this.translateById('ff.wm.group', 'Group')); glabel = glabel.replace(/Viertelfinale/,this.translateById('ff.wm.quarterfinals', 'Quarter-finals')); glabel = glabel.replace(/Halbfinale/,this.translateById('ff.wm.semifinals', 'Semi-finals')); glabel = glabel.replace(/Finale/,this.translateById('ff.wm.final', 'Final')); groupmenu.setAttribute("label", glabel); var groupmenupopup = document.createElement("menupopup"); groupmenu.appendChild(groupmenupopup); groupmenupopup.setAttribute("id", group.id); groupmenupopup.appendChild(scoreboard_vbox); // reorder groups if (group.id.indexOf("Gruppe") == -1 && groupend) { groupItems.reverse(); groupend = false; } if (group.id.indexOf("Gruppe") == -1 && zz < groups.length) { groupItems.push(document.createElement("menuseparator")); } groupItems.push(groupmenu); } else { menupopup.appendChild(scoreboard_vbox); } } groupItems.reverse(); for (var ii=0; ii<groupItems.length; ii++) menupopup.appendChild(groupItems[ii]); //insert table link if (!league.is_tournament) { var menusep = document.createElement("menuseparator"); menupopup.appendChild(menusep); var tablelink = document.createElement("menuitem"); tablelink.setAttribute("id", "tablelink"); tablelink.setAttribute("style", "font-weight:normal;"); var tablelabel = "Display current league table for"; try { tablelabel = this.dictionary.getString("ff.popupmenu.table"); } catch(e) { footiefox_d_message("buildMenu: Translation of table link failed "+e); } tablelabel += " "+ this.getLocalLeagueTitle(league.leagueID) + " ..."; try { tablelink.setAttribute("label", tablelabel); var partnerid = this.checkForLeaguePartner(league.leagueID); tablelink.setAttribute("oncommand", "iFootieFox.openLeagueTable("+games[0].matchID+",15,"+partnerid+")"); menupopup.appendChild(tablelink); } catch (e) { footiefox_d_error(e); } } } this.sortMatchesByTime(); return; }, getLocalLeagueTitle: function(leagueID) { var leaguesDataBundle = this.getCurrentLeaguesDataBundle(); var leaguesDataString = null; try { leaguesDataString = leaguesDataBundle.getString(leagueID); } catch (e) { footiefox_d_error("Failed to match league ID: " + leagueID); } var leaguetitle = "No title"; try { leaguetitle = leaguesDataString.split(":")[0]; } catch (e) {} var intltitle = null; try { intltitle = leaguesDataString.split(":")[4]; } catch (e) {} var loc = this.prefNode.getCharPref("locale"); if ((intltitle != null) && (intltitle !="") && (loc != "de-DE")) { finalLeagueTitle = intltitle; } else { finalLeagueTitle = leaguetitle; } return finalLeagueTitle; }, getLeagueCountryShort: function(leagueID) { var leaguesDataBundle = this.getCurrentLeaguesDataBundle(); var leaguesDataString = null; try { leaguesDataString = leaguesDataBundle.getString(leagueID); } catch (e) { footiefox_d_error("Failed to match league ID: " + leagueID); return ""; } var shortCountry = ""; try { shortCountry = leaguesDataString.split(":")[3]; } catch (e) {} return shortCountry; }, getFirstMatch: function() { var leagues = this.myScoreboard; var match = null; var status = null; var favoriteTeams = new Array(); var teamsToFollow = this.prefNode.getCharPref("teamstofollow"); //if favorite team defined, check scoreboard and pick match if (teamsToFollow!="") { teamsToFollow = teamsToFollow.split(","); var lastmatch = null; for (var u=0; u<teamsToFollow.length; u++) { var teamToFollow = teamsToFollow[u]; for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; status = match.status; var team1Id = match.team1Id; var team2Id = match.team2Id; if ((team1Id == teamToFollow || team2Id == teamToFollow) && (match.status == "scheduled" || match.status == "active" )) return match; if ((team1Id == teamToFollow || team2Id == teamToFollow) && (match.status == "finished")) lastmatch = match; } if (lastmatch != null) return lastmatch; } } } //select first active match for ( var x = 0; x < leagues.length; x++ ) { //if (leagues[x].status!="active") // continue; var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { match = matches[y]; status = match.status; var id = match.matchID; if ( status == "active" ) { return match; } } } //if all matches finished, pick very first one which is scheduled and no placeholder for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { match = matches[y]; if (match.team1Id > 0 && match.status == "scheduled") return match; } } return leagues[0].matches[0]; }, toggleRotate: function () { this.rotation=!this.rotation; this.prefNode.setBoolPref("rotation", this.rotation); if ( this.rotation ) { var rotationintervall = this.prefNode.getIntPref("rotationintervall"); this.ffRotationTimer.initWithCallback(this.rotationTimer, rotationintervall*1000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK); } else { var menuitem_rotate = document.getElementById("ff_popupmenu_rotate"); menuitem_rotate.setAttribute("checked", "false"); this.ffRotationTimer.cancel(); } }, visitWebpage: function( url ) { openUILinkIn(url,"tab"); }, login: function() { var iconnomatches = document.getElementById("deck_minimizedlogo"); iconnomatches.setAttribute("hidden", "true"); this.myScoreboard = new Array(); this.Webservice(); }, webserviceTimeOut: function() { if (this.whatsOnCalled) { this.switchDisplay("no_connection"); } }, Webservice: function (){ try { this.callWhatsOn(false); } catch (e) { footiefox_d_error(e); if ( this.whatsOnCalled ) { var labelnoconnection = document.getElementById("ff_notice_noconnection"); labelnoconnection.setAttribute("hidden", "false"); var labelnomatches = document.getElementById("ff_notice_nomatches"); labelnomatches.setAttribute("hidden", "true"); var labelnoleagues = document.getElementById("ff_notice_noleagues"); labelnoleagues.setAttribute("hidden", "true"); this.minimizeFootieFox(); } } }, SettingsCallback: function (settingsJSON,nocache) { this.failedConnections = 0; iFootieFox.selectedMatch = null; //cache timestamp try { var cacheTimestamp = settingsJSON.cacheTimestamp; if (iFootieFox.prefNode.prefHasUserValue("cachetimestamp")) { var oldTS = iFootieFox.prefNode.getCharPref("cachetimestamp"); if (oldTS != cacheTimestamp) iFootieFox.emptyCache(); } else iFootieFox.emptyCache(); iFootieFox.prefNode.setCharPref("cachetimestamp", cacheTimestamp); } catch(e) {footiefox_d_error("SettingsCallback - Cache timestamp: " + e);} var teamsDataBundle = null; var teamsDataBundleUpdated = document.getElementById("teams-data-bundle-updated"); //updated teams.dat valid if ( teamsDataBundleUpdated.hasAttribute("src") ) teamsDataBundle = teamsDataBundleUpdated; //updated teams.dat corrupt, take inbuilt teams.dat else teamsDataBundle = document.getElementById("teams-data-bundle"); iFootieFox.updateInterval = settingsJSON.updateInterval; iFootieFox.messages = new Array(); try { var messages = settingsJSON.messages; for (var i=0; i<messages.length; i++) { var message = new Object(); message.url = messages[i].url; message.linkurl = messages[i].linkurl; message.linktext = messages[i].linktext; message.time = messages[i].time; iFootieFox.messages.push( message ); } } catch (e) {footiefox_d_error("SettingsCallback - Messages: "+e);} //load banner in menu try { var banners = settingsJSON.banners; iFootieFox.banner = null; if (banners.length > 0 ) { var gDBTPrefService = Components.classes["@mozilla.org/preferences-service;1"] .getService(Components.interfaces.nsIPrefService); var locale = gDBTPrefService.getCharPref("general.useragent.locale"); var b = new Object(); for (var i=0; i<banners.length; i++) { b.imageurl = banners[i].imageurl; b.linkurl = banners[i].linkurl; b.locale = banners[i].locale; if (banners[i].locale == locale) { iFootieFox.banner = b; break; } //default if (banners[i].locale == "xx-XX") iFootieFox.banner = b; } if ( iFootieFox.banner != null ) { var bannerImage = document.getElementById("ff_banner"); var bannerHbox = document.getElementById("ff_bannerhbox"); var bannerSep = document.getElementById("ff_bannersep"); var imageurl = iFootieFox.banner.imageurl; if (imageurl.indexOf("http")!=0) { if (!iFootieFox.inCache(imageurl)) { iFootieFox.cacheFile(iFootieFox.mediaURL + iFootieFox.imagesSubdirectory + imageurl); bannerImage.setAttribute("src", iFootieFox.mediaURL + iFootieFox.imagesSubdirectory + imageurl); } else bannerImage.setAttribute("src", "file://" + iFootieFox.tmpDir + imageurl); } else bannerImage.setAttribute("src", imageurl); bannerHbox.setAttribute("onclick", "iFootieFox.visitWebpage('" + iFootieFox.banner.linkurl + "');"); bannerSep.setAttribute("hidden", "false"); } else { iFootieFox.banner = null; var bannerImage = document.getElementById("ff_banner"); var bannerHbox = document.getElementById("ff_bannerhbox"); var bannerSep = document.getElementById("ff_bannersep"); bannerImage.removeAttribute("src"); bannerHbox.removeAttribute("onclick"); bannerSep.setAttribute("hidden", "true"); } } else { iFootieFox.banner = null; var bannerImage = document.getElementById("ff_banner"); var bannerHbox = document.getElementById("ff_bannerhbox"); var bannerSep = document.getElementById("ff_bannersep"); bannerImage.removeAttribute("src"); bannerHbox.removeAttribute("onclick"); bannerSep.setAttribute("hidden", "true"); } } catch (e) { iFootieFox.banner = null; footiefox_d_error("SettingsCallback - Banner: "+e); } iFootieFox.lastMessage = 0; //load score_ad try { var scoreAds = settingsJSON.scoreAds; iFootieFox.scoreAds = new Array(); if (scoreAds.length > 0 ) { for (var i=0; i<scoreAds.length; i++) { var ad = new Object(); ad.url = scoreAds[i].url; ad.height = scoreAds[i].height; ad.width = scoreAds[i].width; ad.team_id = scoreAds[i].team; ad.league_id = scoreAds[i].league; ad.country_id = scoreAds[i].country; ad.locale = scoreAds[i].locale; ad.priority = scoreAds[i].priority; iFootieFox.scoreAds.push(ad); } } } catch (e) { iFootieFox.scoreAds = null; footiefox_d_error("SettingsCallback - Score Ad: "+e); } iFootieFox.teamslistlasttimestamp = settingsJSON.teamsListTimestamp; iFootieFox.leagueslistlasttimestamp = settingsJSON.leaguesListTimestamp; //show iframe try { iFootieFox.iframes = new Array(); for (var x=0; x<settingsJSON.iframes.length; x++) { var iframe = new Object(); iframe.id = settingsJSON.iframes[x].id; iframe.url = settingsJSON.iframes[x].url; iframe.w = settingsJSON.iframes[x].width; iframe.h = settingsJSON.iframes[x].height; iframe.delay = settingsJSON.iframes[x].delay; iframe.interval = settingsJSON.iframes[x].interval; iframe.datetime = settingsJSON.iframes[x].show_on; iframe.locale = settingsJSON.iframes[x].locale; iFootieFox.iframes.push(iframe); } iFootieFox.processIFrames(); } catch (e) { footiefox_d_error("SettingsCallback - Iframes: "+e); } try { iFootieFox.availableHosts = settingsJSON.hosts.split(","); for (var i=0; i<iFootieFox.availableHosts.length; i++) { iFootieFox.availableHosts[i] = "http://"+iFootieFox.availableHosts[i]+"/"; } var currentHost = iFootieFox.prefNode.getCharPref("host"); if (currentHost == "") { var index = Math.random(); index *= iFootieFox.availableHosts.length; index = Math.ceil(index); iFootieFox.apiURL = iFootieFox.availableHosts[index-1]; iFootieFox.prefNode.setCharPref("host",iFootieFox.apiURL); } } catch (e) { footiefox_d_error("Hosts: "+e); } iFootieFox.requestAllLeagueBases(nocache); }, LeagueBaseCallback: function (leagueJSON) { this.failedConnections = 0; //footiefox_d_message("LeagueBaseCallback: "+ leagueJSON.leagueID); var countriesDataBundle = document.getElementById("countries-data-bundle"); var teamsDataBundle = null; var teamsDataBundleUpdated = document.getElementById("teams-data-bundle-updated"); //updated teams.dat valid if ( teamsDataBundleUpdated.hasAttribute("src") ) teamsDataBundle = teamsDataBundleUpdated; //updated teams.dat corrupt, take inbuilt teams.dat else teamsDataBundle = document.getElementById("teams-data-bundle"); var league = new Object(); league.leagueID = leagueJSON.leagueID; // is this league a tournament? if (typeof(leagueJSON.is_tournament) != 'undefined') league.is_tournament = leagueJSON.is_tournament; else league.is_tournament = false; league.timestamp = leagueJSON.timestamp; league.matches = new Array(); var currentMatches = null; try { currentMatches = leagueJSON.matches; } catch (e) { footiefox_d_error(e); } if (currentMatches.length == 0) { iFootieFox.registerLeagueBaseCallback(); return; } for (var y=0; y<currentMatches.length; y++) { var resMatch = currentMatches[y]; var match = new Object(); match.matchID = resMatch.matchID; var date = iFootieFox.parseDate( resMatch.startTime ); match.startTime = date.getTime(); match.team1Id = resMatch.team1Id; match.team2Id = resMatch.team2Id; match.phase = null; if (typeof(resMatch.phase) != 'undefined') { match.phase = this.getMatchPhase(resMatch.phase); } try { match.team1Title = countriesDataBundle.getString(resMatch.team1Id); } catch (e) { try { var value = teamsDataBundle.getString(resMatch.team1Id); match.team1Title = value.split(":")[1]; } catch (e) { match.team1Title = "<" + iFootieFox.dictionary.getString("ff.notice.notitle") + ">"; } } try { match.team2Title = countriesDataBundle.getString(resMatch.team2Id); } catch (e) { try { var value = teamsDataBundle.getString(resMatch.team2Id); match.team2Title = value.split(":")[1]; } catch (e) { match.team2Title = "<" + iFootieFox.dictionary.getString("ff.notice.notitle") + ">"; } } if (typeof(resMatch.tournament_group) != 'undefined') match.tournament_group = resMatch.tournament_group; match.team1Score = resMatch.team1Score; match.team2Score = resMatch.team2Score; match.status = resMatch.status; match.url = resMatch.url; try { match.url2 = resMatch.url2; } catch (e) {} league.matches.push( match ); } this.myScoreboard.push( league ); this.registerLeagueBaseCallback(); }, registerLeagueBaseCallback: function() { leagueBaseRefreshed += 1; if (leagueBaseRefreshed >= this.myLeagues.length) { iFootieFox.whatsOnCalled = false; //update login timestamp var now = new Date(); var nowTS = now.getTime(); iFootieFox.prefNode.setCharPref("logintimestamp", nowTS); iFootieFox.cacheImages(); iFootieFox.serializeData(); iFootieFox.dataRefreshed(); } }, registerLeagueUpdateCallback: function() { leagueUpdateRefreshed +=1; if (leagueUpdateRefreshed >= iFootieFox.myScoreboard.length) { this.serializeData(); this.dataRefreshed(); } }, registerFailedConnection: function(severity) { this.failedConnections += severity; if (this.failedConnections >= 5) { //reset failure count this.failedConnections = 0; if (this.availableHosts.length > 0) { //remove host from list for (var i=0; i<this.availableHosts.length; i++) { if (this.availableHosts[i] == this.apiURL) { this.availableHosts.splice(i,1); break; } } var index = Math.random(); index *= iFootieFox.availableHosts.length; index = Math.ceil(index); this.apiURL = iFootieFox.availableHosts[index-1]; iFootieFox.prefNode.setCharPref("host",this.apiURL); footiefox_d_error("Connection failed, new server: "+ this.apiURL); //retry with new host setTimeout("iFootieFox.callWhatsOn(false)", 50); } else { this.apiURL = this.first_apiURL; //failed desperately this.webserviceTimeOut(); } } }, LeagueUpdateCallback: function (updateJSON) { footiefox_di_message("LeagueUpdateCallback"); this.failedConnections = 0; var matchDiffs = new Array(); for (var i=0; i<updateJSON.length; i++) { var matchDiff = new Object(); matchDiff.matchId = updateJSON[i].matchID; var match = iFootieFox.getMatch( matchDiff.matchId ); matchDiff.team1Score = updateJSON[i].team1Score; matchDiff.team2Score = updateJSON[i].team2Score; matchDiff.phase = null; if (typeof(updateJSON[i].phase) != 'undefined') { matchDiff.phase = this.getMatchPhase(updateJSON[i].phase); } if (matchDiff.team1Score > match.team1Score) { matchDiff.teamId = match.team1Id; } else if (matchDiff.team2Score > match.team2Score) { matchDiff.teamId = match.team2Id; } else matchDiff.teamId = null; matchDiff.status = updateJSON[i].status; matchDiffs.push(matchDiff); } this.registerLeagueUpdateCallback(); iFootieFox.updateData(matchDiffs, false); }, dataRefreshed: function () { //d("dataRefreshed"); var deckProgressmeter = document.getElementById("deck_progressmeter"); deckProgressmeter.setAttribute("hidden", "true"); if ( this.myScoreboard.length > 0 ) { //build popup menu this.buildMenu(); this.synchronizeTeamsList(); this.synchronizeLeaguesList(); this.displayMatch( this.selectedMatch ); this.ffTimer.initWithCallback(this.updateLeagues, this.updateInterval, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK); } else { //no leagues selected at all if (this.myLeagues.length == 0) { this.switchDisplay("no_leagues"); } else if (failedLeagues == this.myLeagues.length) { this.switchDisplay("no_connection"); //none of the selected leagues are active } else { this.switchDisplay("no_matches"); } } if ( this.messages.length > 0 ) { this.processMessages(); } }, parseDate: function ( datestring ) { if (datestring == null) return null; //var time = datestring.split("T")[1]; //var date = datestring.split("T")[0]; var time = datestring.split(" ")[1]; var date = datestring.split(" ")[0]; var startHrs = parseInt(time.split(":")[0], 10); var startMins = parseInt(time.split(":")[1], 10); var startDay = date.split("-")[2]; var startMonth = parseInt(date.split("-")[1], 10); var startYear = parseInt(date.split("-")[0], 10); var utcdate = new Date(); utcdate.setUTCFullYear( startYear, startMonth -1, startDay ); utcdate.setUTCHours( startHrs, startMins, 0 ); return utcdate; }, checkET: function () { var ET = 0; try { ET = parseInt(this.prefNode.getCharPref("ET")); } catch (e) { this.prefNode.setCharPref("ET", 0); } var now = new Date(); var nowUTC = now.getTime(); if ((nowUTC-ET > 24*60*60*1000) && (this.ETchecking == false)) { this.ETchecking = true; var req = new XMLHttpRequest(); var locale = null; try { locale = this.prefNode.getCharPref("locale"); } catch (e) {} var url = this.redirectURL+"ping?client_id="+this.getSerial()+"&locale="+locale; req.open('GET', url, true); req.onreadystatechange = function (aEvt) { if (req.readyState == 4) { if(req.status == 200) { iFootieFox.prefNode.setCharPref("ET", nowUTC); iFootieFox.ETchecking = false; } else { iFootieFox.ETchecking = false; } } }; req.send(null); } }, callWhatsOn: function (nocache){ footiefox_d_message("callWhatsOn"); this.checkFirstExtension(); if ( !this.firstExtension ) { //false if serialized data outdated if ( this.parseSerializedData() ) { this.dataRefreshed(); return; } } this.switchDisplay("progress"); window.setTimeout("iFootieFox.webserviceTimeOut()", 15000); this.checkET(); this.updateMyLeagues(); this.updateMyTeams(); this.requestSettings(nocache); }, requestAllLeagueBases: function(nocache) { if ( this.myLeagues.length > 0 || this.optionsClosed) { this.optionsClosed = false; this.checkFirstExtension(); if ( !this.firstExtension ) { //false if serialized data outdated if ( this.parseSerializedData() ) { this.dataRefreshed(); return; } } this.whatsOnCalled = true; iFootieFox.myScoreboard = new Array(); leagueBaseRefreshed = 0; failedLeagues = 0; if (this.myLeagues.length == 0) this.switchDisplay("no_leagues"); for (var i=0; i<this.myLeagues.length; i++) { try { this.requestLeagueBase(this.myLeagues[i], nocache); } catch (e) { footiefox_d_error("requestLeagueBase failed for league "+this.myLeagues[i] +": "+e); leagueBaseRefreshed +=1; //footiefox_d_error("catch request"+leagueBaseRefreshed); if (leagueBaseRefreshed >= this.myLeagues.length) { this.dataRefreshed(); } } } } else { this.switchDisplay("no_leagues"); } }, switchDisplay: function(status) { var labelnoleagues = document.getElementById("ff_notice_noleagues"); var labelnomatches = document.getElementById("ff_notice_nomatches"); var labelnoconnection = document.getElementById("ff_notice_noconnection"); var deck_team1 = document.getElementById("deck_team1"); var deck_team2 = document.getElementById("deck_team2"); var deck_score = document.getElementById("deck_score"); var deckProgressmeter = document.getElementById("deck_progressmeter"); var iconnomatches = document.getElementById("deck_minimizedlogo"); switch (status) { case "no_leagues": labelnoleagues.setAttribute("hidden", "false"); labelnomatches.setAttribute("hidden", "true"); labelnoconnection.setAttribute("hidden", "true"); this.minimizeFootieFox(); break; case "no_matches": labelnoleagues.setAttribute("hidden", "true"); labelnomatches.setAttribute("hidden", "false"); labelnoconnection.setAttribute("hidden", "true"); this.minimizeFootieFox(); break; case "progress": deck_team1.setAttribute ("hidden", "true"); deck_team2.setAttribute ("hidden", "true"); deck_score.setAttribute ("hidden", "true"); deckProgressmeter.setAttribute("hidden", "false"); iconnomatches.setAttribute("hidden", "true"); break; case "match": deck_team1.setAttribute ("hidden", "false"); deck_team2.setAttribute ("hidden", "false"); deck_score.setAttribute ("hidden", "false"); labelnomatches.setAttribute("hidden", "true"); labelnoconnection.setAttribute("hidden", "true"); labelnoleagues.setAttribute("hidden", "true"); iconnomatches.setAttribute("hidden", "true"); break; case "minimized": deck_team1.setAttribute ("hidden", "true"); deck_team2.setAttribute ("hidden", "true"); deck_score.setAttribute ("hidden", "true"); deckProgressmeter.setAttribute("hidden", "true"); iconnomatches.setAttribute("hidden", "false"); break; case "no_connection": labelnoconnection.setAttribute("hidden", "false"); labelnomatches.setAttribute("hidden", "true"); labelnoleagues.setAttribute("hidden", "true"); this.minimizeFootieFox(); break; } }, requestSettings: function(nocache) { footiefox_d_message("requestSettings"); var request = new XMLHttpRequest(); request.onreadystatechange = function() { try { if (request.readyState == 4 ) { if ( request.status == 200) { var jsonObject = eval('(' + request.responseText + ')'); iFootieFox.SettingsCallback(jsonObject,nocache); } if ( request.status == 404 || request.status == 0 || request.status == 408 || request.status == 500 || request.status == 503 || request.status == 504 ) { footiefox_d_error("requestSettings failed: " + request.status); iFootieFox.registerFailedConnection(5); } } } catch (e) { footiefox_d_message("requestSettings: "+ e); iFootieFox.registerFailedConnection(5); } } request.open("GET", this.apiURL + "/settings.json"); request.send(null); }, requestLeagueBase: function(id, nocache) { //footiefox_d_message("requestLeagueBase: "+id); var request = new XMLHttpRequest(); request.onreadystatechange = function() { try { if (request.readyState == 4 ) { if ( request.status == 200) { var jsonObject = eval('(' + request.responseText + ')'); iFootieFox.LeagueBaseCallback(jsonObject); } if ( request.status == 404 || request.status == 0 || request.status == 408 || request.status == 500 || request.status == 503 || request.status == 504 ) { failedLeagues +=1; footiefox_d_error("league base request for league " + id +" failed permanently"); footiefox_d_error("requestLeagueBase failed: " + request.status); iFootieFox.registerFailedConnection(1); } } } catch (e) { //FootieFox: requestLeagueBase ...: [Exception... "Component returned failure code: 0x80040111 //(NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" //location: "JS frame :: chrome://footiefox/content/footiefox.js :: anonymous :: line 4116" data: no] iFootieFox.registerFailedConnection(1); //request failed, retry footiefox_d_error("requestLeagueBase ...: "+e); window.setTimeout("iFootieFox.requestLeagueBase("+id+")", 10000); } } request.open("GET", this.apiURL + "leagues/"+id+"/base.json"); // if (nocache) { request.setRequestHeader("Cache-Control", "no-cache"); request.setRequestHeader("Pragma", "no-cache"); request.setRequestHeader("If-Modified-Since", "Thu, 1 Jan 1970 00:00:00 GMT"); } request.send(null); }, requestLeagueUpdate: function(id) { //footiefox_d_message("requestLeagueUpdate: "+id); var request = new XMLHttpRequest(); request.onreadystatechange = function() { try { if (request.readyState == 4) { if (request.status == 200) { var jsonObject = eval('(' + request.responseText + ')'); iFootieFox.LeagueUpdateCallback(jsonObject); } if ( request.status == 404 || request.status == 0 || request.status == 408 || request.status == 500 || request.status == 503 || request.status == 504 ) { failedLeagues +=1; footiefox_d_error("league update request for league " + id +" failed permanently"); footiefox_d_error("requestLeagueUpdate failed: " + request.status); iFootieFox.registerFailedConnection(1); } } } catch (e) { footiefox_d_error("request for league "+ id + " failed:"+e); iFootieFox.registerLeagueUpdateCallback(); iFootieFox.registerFailedConnection(1); //request failed //alert("request for league "+ id + " failed:"+e); } } request.open("GET", this.apiURL + "leagues/"+id+"/update.json"); request.send(null); }, processMessages: function() { var messages = this.messages; this.messageTimer = new Array(); for ( var x = 0; x < messages.length; x++ ) { var message = messages[x]; var url = message.url; var fileName = url.substring(url.lastIndexOf('/')+1, url.length); if (!this.inCache(fileName)) this.cacheFile(url, false); var datetime = message.time; var date = this.parseDate( datetime ); var waitingTime = this.messureTime( date ); var timer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer); var showMessage = { notify: function() { iFootieFox.checkFirstExtension(); if ( iFootieFox.firstExtension ) iFootieFox.messageAlert(); } }; timer.initWithCallback(showMessage, waitingTime*1000, Components.interfaces.nsITimer.TYPE_ONE_SHOT); this.messageTimer.push (timer); } }, processIFrames: function() { var iframes = this.iframes; if (this.iframeTimer.length>0 ) { for (var z=0; z<this.iframeTimer.length; z++) this.iframeTimer[z].cancel(); } var locale = this.prefNode.getCharPref("locale"); this.iframeTimer = new Array(); for ( var x = 0; x < iframes.length; x++ ) { var iframe = iframes[x]; //skip if locale different if ( !(iframe.locale == locale || iframe.locale == "xx-XX") ) continue; var waitingTime = 0; if ( iframe.datetime!=null && iframe.datetime!="") { var date = this.parseDate( iframe.datetime ); waitingTime = this.messureTime( date ); } else { waitingTime = iframe.delay; } var firstTimer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer); var repeatingTimer = Components.classes["@mozilla.org/timer;1"].createInstance(Components.interfaces.nsITimer); var showIFrame = { id: 0, url: "", w: 0, h:0, init: function(id, url, w, h) { this.id = id; this.url = url; this.w = w; this.h = h; }, notify: function() { iFootieFox.checkFirstExtension(); if ( iFootieFox.firstExtension ) iFootieFox.displayIFrame(this.id, this.url, this.w, this.h); } }; showIFrame.init(iframe.id, iframe.url, iframe.w, iframe.h); if (waitingTime > 0) { firstTimer.initWithCallback(showIFrame, waitingTime*1000, Components.interfaces.nsITimer.TYPE_ONE_SHOT); } /*else { firstTimer.initWithCallback(showIFrame, iframe.delay*1000, Components.interfaces.nsITimer.TYPE_ONE_SHOT); repeatingTimer.initWithCallback(showIFrame, iframe.interval*1000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK); this.iframeTimer.push (repeatingTimer); }*/ this.iframeTimer.push (firstTimer); } }, emptyCache: function () { //tmp dir not set if (!this.tmpDir || this.tmpDir == "") return; //tmpDir contains name of cache folder if (this.tmpDir.search(this.cacheFolder)> -1 ) { var directory = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); directory.initWithPath(this.tmpDir); try { directory.remove(true); } catch (e) { footiefox_d_error(e);} //reset timestamps this.prefNode.setCharPref("leagueslisttimestamp", ""); this.prefNode.setCharPref("teamslisttimestamp", ""); } }, messureTime: function ( date ) { var now = new Date(); var waitingTime = date.getTime() - now.getTime(); //returns seconds return Math.round(waitingTime/1000); }, compareMatches: function (a, b) { var aStartTime = a.startTime; var bStartTime = b.startTime; if (aStartTime < bStartTime) return -1; if (aStartTime > bStartTime) return 1; return 0; }, sortMatchesByTime: function () { //d("sortMatchesByTime"); for ( var x = 0; x < this.myScoreboard.length; x++ ) { this.myScoreboard[x].matches.sort(this.compareMatches); } }, synchronizeTeamsList: function() { //d("synchronizeTeamsList"); if (!this.inCache("teams.dat") || this.teamslistlasttimestamp != this.prefNode.getCharPref("teamslisttimestamp")) { this.cacheFile (this.apiURL + "teams.dat", true); this.prefNode.setCharPref("teamslisttimestamp", this.teamslistlasttimestamp); } }, synchronizeLeaguesList: function() { //d("synchronizeLeaguesList"); if (!this.inCache("leagues.dat") || this.leagueslistlasttimestamp != this.prefNode.getCharPref("leagueslisttimestamp")) { this.cacheFile (this.apiURL + "leagues.dat", true); this.prefNode.setCharPref("leagueslisttimestamp", this.leagueslistlasttimestamp); } }, cacheImages: function() { //d("cacheImages"); var leagues = this.myScoreboard; //small logos first for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if (match.team1Id != -1) { this.cacheFile (this.mediaURL + this.imagesSubdirectory + match.team1Id + ".png", false); } if (match.team2Id != -1) { this.cacheFile (this.mediaURL + this.imagesSubdirectory + match.team2Id + ".png", false); } } } //cache menu header this.cacheFile (this.mediaURL + this.imagesSubdirectory + "contextmenuheader.png", false); //now the big ones for ( var x = 0; x < leagues.length; x++ ) { var matches = leagues[x].matches; for ( var y = 0; y < matches.length; y++ ) { var match = matches[y]; if (match.team1Id != -1) { this.cacheFile (this.mediaURL + this.imagesSubdirectory + match.team1Id + "big.png", false); } if (match.team2Id != -1) { this.cacheFile (this.mediaURL + this.imagesSubdirectory + match.team2Id + "big.png", false); } } } }, minimizeFootieFox: function() { this.switchDisplay("minimized"); var deck_footiefox_arrow = document.getElementById("deck_footiefox_arrow"); var footiefox_statusbarpanel = document.getElementById("footiefox_statusbarpanel"); if (this.prefNode.prefHasUserValue("discretemode")) if (!this.prefNode.getBoolPref("discretemode")) { footiefox_statusbarpanel.setAttribute ("collapsed", "false"); } else { footiefox_statusbarpanel.setAttribute ("collapsed", "true"); } var mainPopupSet = document.getElementById("menupopup_mainmenupopup"); this.removeMenu(); }, updateRotationTimer: function() { var rotationintervall = this.prefNode.getIntPref("rotationintervall"); this.ffRotationTimer.initWithCallback(this.rotationTimer, rotationintervall*1000, Components.interfaces.nsITimer.TYPE_REPEATING_SLACK); }, openOptions: function(tab) { openDialog("chrome://footiefox/content/options.xul", "options", "chrome,dialog,centerscreen", tab); }, openAbout: function() { openDialog("chrome://footiefox/content/about.xul", "about", "chrome"); }, openMessageURL: function() { this.visitWebpage(this.messages[ this.lastMessage - 1 ].linkurl); }, getSerial: function() { var serial = null; try { if (this.prefNode.getBoolPref("serial.agreed")) { if (this.prefNode.prefHasUserValue("serial.number")) { serial = this.prefNode.getCharPref("serial.number"); } } } catch (e) {footiefox_d_error(e)} return serial; }, partnerBannerClicked: function(event, adspaceid,partnerid) { if (event == null || event.button == 0 ) { this.visitWebpage(this.redirectURL+"redirect/"+partnerid+"/"+adspaceid+"?client_id="+this.getSerial()); } }, scoreClicked: function (event) { //left mouse button clicked if (event.button == 0 ) { if ( this.rotation ) { this.toggleRotate(); return; } //inc current game var nextmatch = this.getNextMatch(); this.displayMatch ( nextmatch ); //right mouse button } else if (event.button == 2) { this.buildMenu(); } }, bannerClicked: function (event,partnerid) { //left mouse button clicked if (event == null || event.button == 0) { this.openMatchReport("-1", 1, partnerid); } }, icon1Clicked: function (event, partnerid) { //left mouse button clicked if (event == null || event.button == 0) { this.openMatchReport(this.selectedMatch.team1Id, 2,partnerid); } }, icon2Clicked: function (event, partnerid) { //left mouse button clicked if (event == null || event.button == 0 ) { this.openMatchReport(this.selectedMatch.team2Id, 3, partnerid); } }, contextMenuReportClicked1: function(partnerid) { this.openMatchReport(this.selectedMatch.team1Id, 4,partnerid); }, contextMenuReportClicked2: function(partnerid) { this.openMatchReport(this.selectedMatch.team1Id, 5,partnerid); }, openMatchReport: function(teamid, adspace,partnerid) { if (teamid==undefined) teamid="-1"; var matchid = null; try { matchid = this.selectedMatch.matchID; } catch(e) {} var url = this.redirectURL+"redirect/"+partnerid+"/"+adspace+"/"+matchid+"/"+this.prefNode.getCharPref("locale")+"/"+teamid+"?client_id="+this.getSerial(); this.visitWebpage(url); }, openLeagueTable: function(matchid,adspace,partnerid) { var url = this.redirectURL+"redirect/"+partnerid+"/"+adspace+"/"+matchid+"/"+this.prefNode.getCharPref("locale")+"?client_id="+this.getSerial(); this.visitWebpage(url); }, openTeamNameLocalization: function() { var league = this.getLeagueByMatch ( this.selectedMatch ); var leagueId = league.leagueID; this.visitWebpage("http://en.footiefox.com/database/translate_teams/"+leagueId); }, openTeamInformation: function(icon, adspace) { var teamid = null; if (icon == "1") teamid = this.selectedMatch.team1Id; else teamid = this.selectedMatch.team2Id; this.visitWebpage(this.redirectURL+"redirect/"+this.prefNode.getCharPref("partner")+"/"+adspace+"/"+this.selectedMatch.matchID+"/"+this.prefNode.getCharPref("locale")+"/"+teamid+"?client_id="+this.getSerial()); }, cacheFile: function(src, overwrite, pListener) { if ( this.tmpDir == "" ) return; var fileName = src.substring(src.lastIndexOf('/')+1, src.length); var fileSaving = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); try { fileSaving.initWithPath(this.tmpDir); } catch (e) { footiefox_d_error("Permission missing to access cache directory: "+e); return false; } // This is the directory we will be saving in - Create it in case it's a new folder and/or subfolder try { fileSaving.create(1, 0777); } catch (e) {} fileSaving.initWithPath(this.tmpDir + fileName); //download file if it does not exist yet, if overwriting is forced or if file size of the existing file is very small (the existing file is most probably broken) if (!fileSaving.exists() || overwrite || (fileSaving.exists() && fileSaving.fileSize < 500) ) { var cacheKey = Components.classes['@mozilla.org/supports-string;1'].createInstance(Components.interfaces.nsISupportsString); cacheKey.data = src; var urifix = Components.classes['@mozilla.org/docshell/urifixup;1'].getService(Components.interfaces.nsIURIFixup); var uri = urifix.createFixupURI(src, 0); var hosturi = null; if (uri.host.length > 0) { hosturi = urifix.createFixupURI(uri.host, 0); } var persist = Components.classes['@mozilla.org/embedding/browser/nsWebBrowserPersist;1'].createInstance(Components.interfaces.nsIWebBrowserPersist); if (pListener != null) persist.progressListener = pListener; persist.persistFlags = Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_BYPASS_CACHE | Components.interfaces.nsIWebBrowserPersist.PERSIST_FLAGS_CLEANUP_ON_FAILURE; persist.saveURI(uri, cacheKey, hosturi, null, null, fileSaving); } }, manuallyUpdateTeamsList: function () { var ProgressListener = { onStateChange:function(aProgress,aRequest,aFlag,aStatus) { const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP; if (aFlag & STATE_STOP) { //iFootieFox.login(); Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService) .notifyObservers(null, "footiefoxTeamsListUpdated", ""); } }, onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {} } this.cacheFile (this.apiURL + "teams.dat", true, ProgressListener); }, displayReconnect: function() { var labelnoconnection = document.getElementById("ff_notice_noconnection"); try { labelnoconnection.setAttribute("label", this.dictionary.getString("ff.notice.reconnect")); } catch (e) { labelnoconnection.setAttribute("label", "Reconnect"); } }, displayUnreconnect: function() { var labelnoconnection = document.getElementById("ff_notice_noconnection"); try { labelnoconnection.setAttribute("label", this.dictionary.getString("ff.notice.noconnection")); } catch (e) { labelnoconnection.setAttribute("label", "No connection"); } }, displaySelectLeagues: function() { var labelnoleagues = document.getElementById("ff_notice_noleagues"); try { labelnoleagues.setAttribute("label", this.dictionary.getString("ff.notice.noleagueshover")); } catch (e) { labelnoleagues.setAttribute("label", "Select leagues"); } }, displayUnselectLeagues: function() { var labelnoleagues = document.getElementById("ff_notice_noleagues"); try { labelnoleagues.setAttribute("label", this.dictionary.getString("ff.notice.noleagues")); } catch (e) { labelnoleagues.setAttribute("label", "No leagues selected"); } }, serializeData: function() { footiefox_d_message("serializeData"); var serializedObject = new Object(); try { serializedObject.myScoreboard = this.myScoreboard; serializedObject.messages = this.messages; serializedObject.lastMessage = this.lastMessage; serializedObject.teamslistlasttimestamp = this.teamslistlasttimestamp; serializedObject.leagueslistlasttimestamp = this.leagueslistlasttimestamp; serializedObject.updateInterval = this.updateInterval; serializedObject.myLeagues = this.myLeagues; serializedObject.myTeams = this.myTeams; serializedObject.activeLeagues = this.activeLeagues; serializedObject.leagueTimestamps = this.leagueTimestamps; serializedObject.banner = this.banner; serializedObject.iframes = this.iframes; serializedObject.scoreAds = this.scoreAds; var nowLocal = new Date(); var currentTimestamp = nowLocal.getTime(); serializedObject.timestamp = currentTimestamp; } catch (e) { footiefox_d_error("creation of serialization object failed: "+e); } var myJSONText = toJsonString(serializedObject); //var myJSONText = serializedObject.toJSONString(); //var myJSONText = JSON.stringify(serializedObject); if ( this.tmpDir == "" ) return false; var fileName = "scoreboard.json"; var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(this.tmpDir + fileName); try { var foStream = Components.classes["@mozilla.org/network/file-output-stream;1"] .createInstance(Components.interfaces.nsIFileOutputStream); ////CRASHT HIER!!!!!!! // use 0x02 | 0x10 to open file for appending. foStream.init(file, 0x02 | 0x08 | 0x20, 0664, 0); // write, create, truncate foStream.write(myJSONText, myJSONText.length); foStream.close(); } catch (e) { this.prefNode.setCharPref("tempdir", ""); footiefox_d_error("Failed to create temp folder!"); } //notify non-first extensions to update their scoreboard Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService) .notifyObservers(null, "footiefoxRefreshData", ""); return true; }, parseSerializedData: function() { footiefox_d_message("parseSerializedData"); this.whatsOnCalled = false; var data = ""; try { var fileName = "scoreboard.json"; var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(this.tmpDir + fileName); var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"] .createInstance(Components.interfaces.nsIFileInputStream); var sstream = Components.classes["@mozilla.org/scriptableinputstream;1"] .createInstance(Components.interfaces.nsIScriptableInputStream); fstream.init(file, 1, 0, false); sstream.init(fstream); var str = sstream.read(4096); while (str.length > 0) { data += str; str = sstream.read(4096); } sstream.close(); fstream.close(); } catch (e) { footiefox_d_error("failed to read serialized data file:"+e); return false; } try { //var serializedObject = eval('(' + data + ')'); var serializedObject = data.parseJSON(); //var serializedObject = JSON.parse(data); var timestamp = new Date(serializedObject.timestamp); var currentTimestamp = new Date(); //serialized data outdated (past midnight GMT) if ( timestamp.getUTCDate() != currentTimestamp.getUTCDate() ) { if(serializedObject == false) { footiefox_d_error("serialized data is corrupted!"); } else { footiefox_d_error("serialized data outdated"); } return false; } this.myScoreboard = serializedObject.myScoreboard; this.messages = serializedObject.messages; this.lastMessage = serializedObject.lastMessage; this.teamslistlasttimestamp = serializedObject.teamslistlasttimestamp; this.leagueslistlasttimestamp = serializedObject.leagueslistlasttimestamp; this.updateInterval = serializedObject.updateInterval; this.myLeagues = serializedObject.myLeagues; this.myTeams = serializedObject.myTeams; this.activeLeagues = serializedObject.activeLeagues; this.leagueTimestamps = serializedObject.leagueTimestamps; this.banner = serializedObject.banner; this.iframes = serializedObject.iframes; this.scoreAds = serializedObject.scoreAds; try { this.processMessages(); this.processIFrames(); } catch (e) { footiefox_d_error("parseSerializedData: "+e); } } catch (e) { footiefox_d_error("failed to read serialized data " + e); return false; } this.fixUTF8Names(); return true; }, fixUTF8Names: function() { var countriesDataBundle = document.getElementById("countries-data-bundle"); var teamsDataBundle = null; var teamsDataBundleUpdated = document.getElementById("teams-data-bundle-updated"); //updated teams.dat valid if ( teamsDataBundleUpdated.hasAttribute("src") ) teamsDataBundle = teamsDataBundleUpdated; //updated teams.dat corrupt, take inbuilt teams.dat else teamsDataBundle = document.getElementById("teams-data-bundle"); //country names with special UTF8 codes are not properly written to the JSON file //here we assign them again from countries.dat for (var i=0; i<this.myScoreboard.length; i++) { var league = this.myScoreboard[i]; var matches = league.matches; //localized country names for (var x=0; x<matches.length; x++) { var match = matches[x]; try { match.team1Title = countriesDataBundle.getString(match.team1Id); } catch (e) { try { var value = teamsDataBundle.getString(match.team1Id); match.team1Title = value.split(":")[1]; } catch (e) { match.team1Title = "<" + iFootieFox.dictionary.getString("ff.notice.notitle") + ">"; } } try { match.team2Title = countriesDataBundle.getString(match.team2Id); } catch (e) { try { var value = teamsDataBundle.getString(match.team2Id); match.team2Title = value.split(":")[1]; } catch (e) { match.team2Title = "<" + iFootieFox.dictionary.getString("ff.notice.notitle") + ">"; } } league.matches[x] = match; } this.myScoreboard[i] = league; } }, statusbarArrowClicked: function(event) { if ( event.button == 0 ) { this.buildMenu(); var contextmenu = document.getElementById('menupopup_mainmenupopup'); var deck_footiefox_arrow = document.getElementById('deck_footiefox_arrow'); contextmenu.showPopup(deck_footiefox_arrow,-1,-1,'context','topleft','bottomleft'); } }, statusbarArrowHover: function() { var arrow = document.getElementById('ff_contextmenu_arrow'); arrow.setAttribute("style","list-style-image: url('chrome://global/skin/arrow/arrow-up.gif');margin-right:0px;margin-left:0px;margin-top:8px;margin-bottom:10px;min-height:3px;max-height:3px;max-width:5px;"); }, statusbarArrowOut: function() { var arrow = document.getElementById('ff_contextmenu_arrow'); arrow.setAttribute("style","list-style-image: url('chrome://footiefox/skin/arrow-up-green.gif');margin-right:0px;margin-left:0px;margin-top:8px;margin-bottom:10px;min-height:3px;max-height:3px;max-width:5px;"); }, getLocalPartner: function(loc) { var partnersEnum = this.partners.strings; var index = -1; while (partnersEnum.hasMoreElements()) { try { var element = partnersEnum.getNext(); var key = element.QueryInterface(Components.interfaces.nsIPropertyElement).key; var value = element.QueryInterface(Components.interfaces.nsIPropertyElement).value; if (value.split(":")[0]==loc) { index = key; break; } } catch(ex){ footiefox_d_error(ex); continue; } } return index; }, applyPartnerOverlay: function() { var partner = null; var partnerNum = this.prefNode.getCharPref("partner"); var menupopup_icon1_propose = document.getElementById("menupopup_icon1_propose"); var menupopup_icon2_propose = document.getElementById("menupopup_icon2_propose"); var menupopup_icon1_sep = document.getElementById("menupopup_icon1_sep"); var menupopup_icon2_sep = document.getElementById("menupopup_icon2_sep"); try { // find locale partner partner = this.partners.getString(this.getLocalPartner(this.prefNode.getCharPref("locale"))).split(":")[1]; menupopup_icon1_propose.setAttribute("collapsed","true"); menupopup_icon2_propose.setAttribute("collapsed","true"); menupopup_icon1_sep.setAttribute("hidden","true"); menupopup_icon2_sep.setAttribute("hidden","true"); } catch (e) { // no locale partner partner = this.partners.getString(partnerNum).split(":")[1]; menupopup_icon1_propose.setAttribute("label", "Propose local partner for '" + this.prefNode.getCharPref("locale") +"'"); menupopup_icon2_propose.setAttribute("label", "Propose local partner for '" + this.prefNode.getCharPref("locale") +"'"); menupopup_icon1_propose.setAttribute("collapsed","false"); menupopup_icon2_propose.setAttribute("collapsed","false"); menupopup_icon1_sep.setAttribute("hidden","false"); menupopup_icon2_sep.setAttribute("hidden","false"); } this.addToolbarButtons(); var statusbar = document.getElementById("statusbarpanel_partner_logo"); statusbar.setAttribute("src", "chrome://footiefox/skin/"+partnerNum+"/statusbar.png"); //deck partner logo var label = document.getElementById("deck_partner_logo"); if (!this.prefNode.getBoolPref("partner.statusbarlabel")) { label.setAttribute("hidden", "true"); label.setAttribute("collapsed", "true"); } else { label.setAttribute("hidden", "false"); label.setAttribute("collapsed", "false"); } //goal alert partner banner var alert_partner = document.getElementById("ff_alert_partner"); alert_partner.setAttribute("src", "chrome://footiefox/skin/"+partnerNum+"/goalalert.png"); }, //DEMO triggerGoalManually: function(team) { footiefox_d_message("triggerGoalManually"); try{ var matchDiffs = new Array(); var cmatch = iFootieFox.selectedMatch; var matchDiff = new Object(); matchDiff.matchId = cmatch.matchID; var match = iFootieFox.getMatch( matchDiff.matchId ); matchDiff.team1Score = parseInt(cmatch.team1Score); matchDiff.team2Score = parseInt(cmatch.team2Score); matchDiff.phase = cmatch.phase; if (team == 0) { matchDiff.team1Score +=1; matchDiff.teamId = match.team1Id; } else { matchDiff.team2Score +=1; matchDiff.teamId = match.team2Id; } matchDiff.status = cmatch.status; matchDiffs.push(matchDiff); this.updateData(matchDiffs,0); } catch (e) { footiefox_d_error(e); } } }; function playAlarmSound(sURL_str) { var sample = iFootieFox.soundPlayer.QueryInterface(Components.interfaces.nsISound); var ioService = Components.classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var url = ioService.newURI(sURL_str, null, null); sample.play(url); } // Dump a message to Javascript Console function footiefox_d_message(msg){ if (footiefox_d == 1) { var acs = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService); acs.logStringMessage("FootieFox: " + msg); } } function footiefox_d_error(msg){ var acs = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService); acs.logStringMessage("FootieFox: " + msg); } function footiefox_di_message(msg) { if (footiefox_d == 1) { var jetzt = new Date(); footiefox_d_error(msg + ": " + jetzt); } } function dscore() { //debug scoreboard list for (var x=0; x<iFootieFox.myScoreboard.length; x++) { var league = iFootieFox.myScoreboard[x]; var matches = league.matches; for (var y=0; y<matches.length; y++) { var match = matches[y]; var dat = new Date(); dat.setTime(match.startTime), footiefox_d_message( dat + " " + match.team1Title + match.team2Title); } } } function myObservers() { this.register(); } myObservers.prototype = { observe: function(subject, topic, data) { if (topic == "alertclickcallback") window.setTimeout("iFootieFox.openMessageURL()", 0); if (topic == "footiefoxRefreshData") { //iFootieFox.removeMenu(); if (!iFootieFox.firstExtension) if ( iFootieFox.parseSerializedData() ) iFootieFox.dataRefreshed(); } if (topic == "footiefoxTriggerUpdate") { //iFootieFox.browserStartUp = false; iFootieFox.optionsClosed = true; setTimeout("iFootieFox.callWhatsOn(true)", 50); } if (topic == "footiefoxManuallyUpdateTeamsList") { setTimeout("iFootieFox.manuallyUpdateTeamsList()", 0); } if (topic == "footiefoxUpdateRotation") if (iFootieFox.rotation) window.setTimeout("iFootieFox.updateRotationTimer()", 0); if (topic == "footiefoxMaximized") iFootieFox.checkWindowMaximized(); if (topic == "footiefoxGoalAlert") { iFootieFox.updateAlertSlider(data); iFootieFox.showSlider(); } if (topic == "footiefoxOptionsClosed") { iFootieFox.displayMatch(iFootieFox.selectedMatch); iFootieFox.applyPartnerOverlay(); //iFootieFox.dataRefreshed(); window.setTimeout("iFootieFox.dataRefreshed()",0); } if (topic == "footiefoxWizardFinished") { iFootieFox.applyPartnerOverlay(); if (data=="true") iFootieFox.openOptions('ff_options_tabs_leagues'); if (!iFootieFox.isSearchEngineInstalled()) iFootieFox.addSearchEngine(); } }, register: function() { iFootieFox.checkFirstExtension(); var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.addObserver(this, "footiefoxTriggerUpdate", false); observerService.addObserver(this, "footiefoxUpdateRotation", false); observerService.addObserver(this, "footiefoxRefreshData", false); observerService.addObserver(this, "footiefoxMaximized", false); observerService.addObserver(this, "footiefoxGoalAlert", false); observerService.addObserver(this, "footiefoxOptionsClosed", false); observerService.addObserver(this, "footiefoxManuallyUpdateTeamsList", false); observerService.addObserver(this, "footiefoxWizardFinished", false); }, unregister: function() { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); if (iFootieFox.firstExtension) { observerService.removeObserver(iFootieFox, "footiefoxExtension"); } observerService.removeObserver(this, "footiefoxTriggerUpdate"); observerService.removeObserver(this, "footiefoxUpdateRotation"); observerService.removeObserver(this, "footiefoxRefreshData"); observerService.removeObserver(this, "footiefoxMaximized"); observerService.removeObserver(this, "footiefoxGoalAlert"); observerService.removeObserver(this, "footiefoxOptionsClosed"); observerService.removeObserver(this, "footiefoxManuallyUpdateTeamsList"); observerService.removeObserver(this, "footiefoxWizardFinished"); } } function inArray(element, list) { for (var i=0; i<list.length; i++) { if (list[i] == element) return true; } return false; } function whereIsFootieFox() { var eleBrowser = getBrowser(); eleBrowser.contentWindow.packageExists = 12; }